如何检测一个 youtube 视频何时结束播放?

我正在一个网站上工作,有一吨嵌入的 youtube 视频,客户端希望显示一个弹出窗口时,一个视频停止播放。

我查看了 youtube 应用程序接口,似乎有一种方法可以检测视频何时结束:

Http://code.google.com/apis/youtube/js_api_reference.html

但是我不能像他们在页面上提到的那样嵌入视频,因为视频都已经在网站上了(成千上万的视频是通过粘贴嵌入代码手动添加的)。

有没有一种方法可以检测这些视频的结束而不改变任何现有的视频(使用 javascript) ?

116094 次浏览

What you may want to do is include a script on all pages that does the following ... 1. find the youtube-iframe : searching for it by width and height by title or by finding www.youtube.com in its source. You can do that by ... - looping through the window.frames by a for-in loop and then filter out by the properties

  1. inject jscript in the iframe of the current page adding the onYoutubePlayerReady must-include-function http://shazwazza.com/post/Injecting-JavaScript-into-other-frames.aspx

  2. Add the event listeners etc..

Hope this helps

This can be done through the youtube player API:

http://jsfiddle.net/7Gznb/

Working example:

    <div id="player"></div>


<script src="http://www.youtube.com/player_api"></script>


<script>


// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
width: '640',
height: '390',
videoId: '0Bmhjf0rKe8',
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
});
}


// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}


// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('done');
}
}


</script>