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

标签 javascript youtube youtube-api greasemonkey

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

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

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

这里是the complete script (right-click to save)的相关部分:

... ...

//-- 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!");
    }
}

... ...


谢谢:-)

最佳答案

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

  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 来查看存储的值。

关于javascript - 如何从必须在目标页面范围内运行的代码调用 Greasemonkey 的 GM_ 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14229539/

相关文章:

javascript - 带有 gstreamer 的 JSMPEG 相机流

youtube - Youtube?rel = 0标签不再起作用

wpf - 如何在 Windows 8 Metro 应用程序中播放 Youtube 或实时流协议(protocol)视频?

youtube - 使用 Google YouTube V3 API 未检索到回复或未检索到所有评论

javascript - 如何防止 Javascript/JQuery 移动页面上的其他元素?

javascript - 使用 jQuery AJAX 和 ASP.NET 与数据库通信

javascript - 将 YouTube 视频插入弹出窗口

python - 抓取 youtube 数据的合法性是什么?

php - 使用 PHP for 和 foreach 循环从 JSON 数据中检索视频信息时遇到问题 - YouTube API 3

javascript - 获取对象中元素的路径,而不循环遍历所有元素(第二层次结构级别未知)