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>
我创建了一个简单的 codepen 来监控问题 here .此示例的大部分内容是 official docs 中的示例之一的直接副本。 .
最佳答案
[编辑] 从此 Google Issue Tracker 找到解决方案.好像是浏览器的问题。
试试那些:
希望有帮助🙃
===
你不是一个人!我有使用
on...
的代码几天前工作的事件(onReady
等)突然停止工作而没有更改代码。react-youtube
这样的子库。 (见 Issue #260 ) 看起来它开始于 9 月 9 日,与 Youtube Data API 版本一致(参见 revision history for Sept. 9)。但我在他们的列表中看不到任何会损害 iframe 事件/功能的东西🤔
这就是我所取得的成就,希望能给某人一个提示,以解决这个问题。 🤷🏼♂️ 将在发现时更新此评论。
关于javascript - YouTube 播放器 API 未按文档说明工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63921369/