我在使用 Google Chrome 和 Edge 时遇到问题,没有发生 YouTube 视频事件。我需要知道视频何时结束。我使用了 YouTube 的 iFrame API 中的代码。这些事件在 Safari 中正常运行。
这里是 HTML 和 Javascript 代码:
<iframe id="player" type="text/html" width="640" height="390"
src="https://www.youtube.com/embed/xPxk0zvqes4? enablejsapi=1&origin=https://mishparking.com"
frameborder="0"></iframe>
var tag = document.createElement('script');
Javascript:
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
playerVars: {
'playsinline': 1
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
if(event.data == YT.PlayerState.ENDED) {
alert("Video has ended.");
}
}
function stopVideo() {
player.stopVideo();
}
我在OP中看到的唯一一件事是URL在
enablejsapi=1
之前有一个空格。为简洁起见,在获取 event.data
的值时,将其用作简单数字,而不是 .playerState
属性。下面的示例不适用于 SO,所以如果您想查看一个功能示例,请转到此fiddle。
const tag = document.createElement("script");
tag.src = "https://www.youtube.com/iframe_api";
const firstTag = document.querySelector("script");
firstTag.insertAdjacentElement("beforebegin", tag);
const view = document.querySelector("#message");
let ytPlayer;
function onYouTubeIframeAPIReady() {
ytPlayer = new YT.Player("ytFrame", {
events: {
"onReady": onPlayerReady,
"onStateChange": onPlayerStateChange
}
});
}
function onPlayerReady(event) {
view.value = "Video is ready";
}
function playerStatus(status) {
switch (status) {
case 0:
view.value = "Video has ended";
break;
case 1:
view.value = "Video is playing";
break;
case 2:
view.value = "Video is paused";
break;
default:
break;
}
}
function onPlayerStateChange(event) {
playerStatus(event.data);
}
#ytFrame {
display: block;
}
#message {
display: inline-block;
width: 320px;
height: 25px;
font-family: "Segoe UI";
text-align: center;
color: gold;
background: black;
}
<iframe id="ytFrame" src="https://www.youtube.com/embed/4r7wHMg5Yjg?enablejsapi=1" width="320" height="180" frameborder="0"></iframe>
<output id="message"></output>