Control Youtube video player using Javascript from FireFox addon
I wrote a FireFox addon which has a button on the toolbar. On click event, I am trying to find the EMBED element and try to call pauseVideo() on it, but it doesn't work.
I am sure the object I get is the EMBED so no doubt about that, because I display the 'src'
var p1 = content.document.getElementById("movie_player");
window.alert(p1.src);
The problem is pauseVideo() doesn't work:
try
{
p1.pauseVideo(开发者_如何学运维);
}
catch(e)
{
window.alert(e); // this gives 'pauseVideo() is not a function'
}
Also, the 'allowscriptaccess' attribute is set to 'always'. Any idea why it doesn't work? I am out of ideas.
Thanks!
Make sure the enablejsapi
is set.
https://developers.google.com/youtube/player_parameters#enablejsapi
You need to use postMessage to communicate with Youtube player, something like this:
var doc = content.document;
var scpt = doc.getElementById("uniq_script_id");
if (!scpt) {
scpt = doc.createElement("script");
scpt.type = "text/javascript";
scpt.id = "uniq_script_id";
var code = [
'window.addEventListener("message", function(e) {',
' var cmd = e.data;',
' var player = document.getElementById("movie_player");',
' player[cmd]();',
'}, false);'
].join('\n');
scpt.textContent = code;
doc.body.appendChild(scpt);
}
window.postMessage("pauseVideo", "*");
精彩评论