我想编写一个 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');
}
这个问题有解决办法还是根本不可能?
请您参考如下方法:
"the problem is just the listener on "onStateChange" "
好吧,为了解决一些范围界定问题,最好只注入(inject)与 YouTube API 交互的代码。
以下内容适用于 Firefox+Greasemonkey、Chrome 或 Chrome+Tampermonkey。它也应该适用于任何支持用户脚本的浏览器:
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);
}