Javascript 如何检测youtube视频何时播放完毕?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7853904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect when a youtube video finishes playing?
提问by TK123
I am working on a site that has a ton of embedded youtube videos, the client wants to show a popup whenever a video stops splaying.
我正在一个有大量嵌入式 YouTube 视频的网站上工作,客户端希望在视频停止播放时显示一个弹出窗口。
I looked at the youtube api and there seems to be a way to detect when a video ends:
我查看了 youtube api,似乎有一种方法可以检测视频何时结束:
http://code.google.com/apis/youtube/js_api_reference.html
http://code.google.com/apis/youtube/js_api_reference.html
but I can't embed the videos like they mentioned on that page since the videos are all already on the site (thousands that have been added manually by pasting embed code).
但我无法像他们在该页面上提到的那样嵌入视频,因为这些视频都已经在网站上(通过粘贴嵌入代码手动添加了数千个)。
Is there a way to detect the ending of these videos without changing any of the existing videos (using javascript)?
有没有办法在不更改任何现有视频的情况下检测这些视频的结尾(使用 javascript)?
回答by TK123
This can be done through the youtube player API:
这可以通过 youtube 播放器 API 完成:
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>
回答by yshouman
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. 找到 youtube-iframe :按标题的宽度和高度搜索它,或者在其源中找到 www.youtube.com。你可以这样做... - 通过 for-in 循环遍历 window.frames,然后通过属性过滤掉
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
Add the event listeners etc..
在当前页面的 iframe 中注入 jscript 添加 onYoutubePlayerReady must-include-function http://shazwazza.com/post/Injecting-JavaScript-into-other-frames.aspx
添加事件侦听器等。
Hope this helps
希望这可以帮助