如何从必须在目标页面范围内运行的代码调用 Greasemonkey 的 GM_ 函数?

IT技术 javascript youtube youtube-api greasemonkey
2021-02-28 20:22:51

我在这里问了一个问题并得到了答案:How to call this YouTube function from Greasemonkey?

该代码有效并向页面添加了一个按钮,用于捕获视频时间。
但是,关键部分必须在目标页面范围内运行——在那里 Greasemonkey 的GM_功能不可用。

我想用来GM_setValue()录制视频时间。如何GM_setValue()从按钮的click处理程序调用

这是完整脚本的相关部分(右键单击保存)

... ...

//-- Only run in the top page, not the various iframes.
if (window.top === window.self) {
    var timeBtn         = document.createElement ('a');
    timeBtn.id          = "gmTimeBtn";
    timeBtn.textContent = "Time";
    //-- Button is styled using CSS, in GM_addStyle, below.

    document.body.appendChild (timeBtn);

    addJS_Node (null, null, activateTimeButton);
}

function activateTimeButton () {
    var timeBtn = document.getElementById ("gmTimeBtn");
    if (timeBtn) {
        timeBtn.addEventListener ('click',
            function () {
                var ytplayer = document.getElementById ("movie_player");
                //-- IMPORTANT:  GM_functions will not work here.

                console.log ("getCurrentTime(): ", ytplayer.getCurrentTime() );
                alert (ytplayer.getCurrentTime() );
            },
            false
        );
    }
    else {
        alert ("Time button not found!");
    }
}

... ...


谢谢 :-)

1个回答

要从GM_必须在页面范围内运行的代码(例如您的timeBtn点击处理程序)中使用 Greasemonkey 的函数,请执行以下操作:

  1. 使用页面范围代码postMessage以字符串格式发送数据。
  2. 让 Greasemonkey 脚本侦听适当的消息并GM_使用消息数据调用所需的函数。
  3. 使用 JSON 将数据安全地打包成字符串。

window.postMessage ()添加window.addEventListener ("message"...到您的代码中,它将变为:

... ...

//-- Only run in the top page, not the various iframes.
if (window.top === window.self) {
    var timeBtn         = document.createElement ('a');
    timeBtn.id          = "gmTimeBtn";
    timeBtn.textContent = "Time";
    //-- Button is styled using CSS, in GM_addStyle, below.

    document.body.appendChild (timeBtn);

    addJS_Node (null, null, activateTimeButton);

    window.addEventListener ("message", receiveTimeMessage, false);
}

function activateTimeButton () {
    var timeBtn = document.getElementById ("gmTimeBtn");
    if (timeBtn) {
        timeBtn.addEventListener ('click',
            function () {
                var ytplayer = document.getElementById ("movie_player");
                /*-- GM_functions will not work here, so send the data
                    back to the GM script scope.
                */
                //-- Tag the message, we may not be the only ones sending.
                var messageTxt  = JSON.stringify (
                    {currentVidTime: ytplayer.getCurrentTime ()}
                );
                window.postMessage (messageTxt, "*");
            },
            false
        );
    }
    else {
        alert ("Time button not found!");
    }
}

function receiveTimeMessage (event) {
    var messageJSON;
    try {
        messageJSON     = JSON.parse (event.data);
    }
    catch (zError) {
        // Do nothing
    }

    if ( ! messageJSON  ||  ! messageJSON.currentVidTime)
        return; //-- Message is not for us.

    /*--- We have a time value, set it with GM_setValue ()
        But, WARNING: First make sure that the stored value is
        a safe string.  GM_setValue() crashes on just about anything else.
    */
    var safeValue       = JSON.stringify (messageJSON.currentVidTime);
    GM_setValue ("videoMarkedTime", safeValue);
    console.log ("Video time recorded with GM_setValue ().");
}

... ...


您可以通过打开about:config并搜索来查看存储的值videoMarkedTime

about:config是 Firefox 的东西。请参阅GM_setValue 在哪里存储数据(对于 Tampermonkey)是的,在执行此类操作的大多数情况下,您都需要字符串化、解析和字符串化。
2021-04-19 20:22:51
您知道我们可以在 Chrome 中的哪个位置看到about:config? 我试着往里面看,about:about但什么也没找到……我们真的需要再次字符串化、解析和字符串化吗?我只是event.data作为对象发送并字符串化到GM_setValue. . . . 很棒的片段,顺便说一句;GM 值很棒,因为它们是跨域的,再次感谢!
2021-05-11 20:22:51