如何使用Greasemonkey调用现有视频的Youtube-Flash-API



我想写一个Greasemonkey脚本来检测一个网站上的YouTube视频何时开始播放,以阻止我的winamp播放音乐。一切工作正常,我的脚本检测视频,启用API,也onYouTubePlayerReady事件被调用。但是我不知道如何注册onStateChange回调,这是我的代码:

unsafeWindow.onYouTubePlayerReady = function (playerId)
{
    alert('Visible');
    document.getElementById(playerId).addEventListener('onStateChange', 'stateChanged');    
    alert('Not visible, so the line above crashes');
}
unsafeWindow.stateChanged = function (state)
{
    alert('never called, too');
}

这个问题有解决办法吗?还是根本不可能?

"问题是监听器在"onStateChange" "

好吧,为了解决一些作用域问题,最好只注入与YouTube API交互的代码。

以下内容适用于Firefox+Greasemonkey,以及Chrome或Chrome+Tampermonkey。它还可以在任何支持userscripts的浏览器上运行:

function GM_main () {
    window.stateChanged = function (state) {
        console.log ('GM: In stateChanged().  State = ', state);
    }
    window.onYouTubePlayerReady = function (playerId) {
        /*-- playerId is not being set by Youtube. Use
            hard-coded id (movie_player) instead.
        */
        var playerNode  = document.getElementById ("movie_player");
        if (playerNode) {
            /*--- Note, inside onYouTubePlayerReady ONLY, the YouTube API
                seems to override addEventListener. Hence the nonstandard
                parameters.
            */
            playerNode.addEventListener ('onStateChange', 'stateChanged');
            console.log ('GM: Listener installed just fine.');
        }
        else
            console.error ("GM: Player node not found!");
    }
}
addJS_Node (null, null, GM_main);
function addJS_Node (text, s_URL, funcToRun, runOnLoad) {
    var D                                   = document;
    var scriptNode                          = D.createElement ('script');
    if (runOnLoad) {
        scriptNode.addEventListener ("load", runOnLoad, false);
    }
    scriptNode.type                         = "text/javascript";
    if (text)       scriptNode.textContent  = text;
    if (s_URL)      scriptNode.src          = s_URL;
    if (funcToRun)  scriptNode.textContent  = '(' + funcToRun.toString() + ')()';
    var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
    targ.appendChild (scriptNode);
}

相关内容

  • 没有找到相关文章

最新更新