【发布时间】:2021-01-03 08:43:10
【问题描述】:
YouTube Player API 目前似乎无法正常工作。播放器将正确初始化,但没有任何方法或事件起作用。
<div class="flex">
<div id="player"></div>
<div id="log"></div>
</div>
<script>
// for convenience
var isPlayerReady = false;
var logEl = document.getElementById('log');
function addToLog(text) {
logEl.innerHTML = logEl.innerHTML + text + '<br>';
}
window.setTimeout(function () {
if (!isPlayerReady) {
addToLog('5 seconds have passed and the player has not fired the onReady event. This is a good indication that the API is not working properly.');
}
}, 5000);
// from here on, the code is a direct copy of an example from the official docs
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
addToLog('onYouTubeIframeAPIReady fired, loading Player');
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
isPlayerReady = true;
addToLog('onPlayerReady fired');
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
addToLog('onPlayerStateChange fired');
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
我创建了一个简单的代码笔来监控问题here。此示例的大部分内容是official docs 中示例之一的直接副本。
【问题讨论】:
-
我在那个 codepen 中看不到任何说明任何错误的东西......你有什么问题(绝对没有错误)
-
在加载时,我看到
onYouTubeIframeAPIReady fired, loading Player onPlayerReady fired onPlayerStateChange fired onPlayerStateChange fired onPlayerStateChange fired,视频在 6 秒后停止... -
@JaromandaX 感谢您使用笔。没有任何错误。请看代码:onPlayerReady,视频应该是自动播放的。
-
哦,这可以被浏览器中的设置覆盖......我当然不允许它
-
@JaromandaX 顺便说一句很奇怪:我没有看到你提到的
onPlayerStateChange fired!
标签: javascript api youtube