我设法让这个脚本工作(整个早上弄乱它),这样视频就会自动播放,而我不必进入并在每个视频的末尾手动添加?autoplay=1
(我有很多已上传的视频)。
我现在需要的是脚本能够检测到视频何时结束并指向另一个页面(此时此页面并不重要,我只是专注于让方向发挥作用。 )
任何人都可以帮助我吗?我无法获取代码来检测youtube视频的结尾。我把它弄乱了还是写错了?我希望此代码适用于现有 Youtube视频,因此我不必进入并手动修复我发布的每个嵌入代码(有很多很多! )
到目前为止,这是我的代码。 (http://jsfiddle.net/26B7D/8/)
//select the first iframe that has a src that starts with "//www.youtube"
var firstIframe = document.querySelector('iframe[src^="https://www.youtube"]');
//get the current source
var src = firstIframe.src;
//update the src with "autoplay=1"
var newSrc = src + '?enablejsapi=1&autoplay=1&showinfo=0&controls=1&rel=0&wmode=transparent&vq=hd1080&hd=1&playerapiid=player';
//change iframe's src
firstIframe.src = newSrc.replace("?feature=oembed", "");
onYouTubePlayerReady = function (playerId) {
ytplayer = document.getElementById("player");
ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
};
// when video ends
function onPlayerStateChange(event) {
if (event.data === 0) {
alert('done');
// window.location = "http://example.com";
}
}
修改
做了很多工作,但我想我找到了一种方法让它适用于现有的YouTube视频。我只掌握了Javascript的基本知识,所以对于大量的猜测和反复试验,我引以为傲。 (哈哈,现在看,当我发布它时它会停止工作。其他人可以查看下面的小提琴和我的代码,并知道它是否真的有效。我还没有睡觉试图解决这个问题所以我可能是妄想.xD)
http://jsfiddle.net/WhR6E/2/show/
<script src="http://www.youtube.com/player_api"></script>
<div id="player"></div>
<div id="test">
<iframe width="500" height="374" src="https://www.youtube.com/embed/JljriNlho6k?feature=oembed" frameborder="0" allowfullscreen></iframe>
</div>
<script>
//select the first iframe that has a src that starts with "//www.youtube"
var firstIframe = document.querySelector('iframe[src^="https://www.youtube"]');
//get the current source
var src = firstIframe.src;
//update the src with "autoplay=1"
var newSrc = src + '?enablejsapi=1&autoplay=1&showinfo=0&controls=1&rel=0&wmode=transparent&vq=hd1080&hd=1&playerapiid=player';
//change iframe's src
firstIframe.src = newSrc.replace("?feature=oembed", "");
var justID = src.replace("https://www.youtube.com/embed/", "");
var justID = justID.replace("?feature=oembed", "");
x = document.getElementById("test").innerHTML = justID;
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: justID,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if (event.data === 0) {
window.location = "http://example.com";
}
}
</script>