YouTube 播放器 API 未按记录运行

YouTube Player API is not working as documented

似乎 YouTube 播放器 API 目前无法正常工作。播放器将正确初始化,但 none 的方法或事件正在运行。

<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. Most of this example is a direct copy of one of the examples in the official docs

[编辑] 从这个 Google Issue Tracker 中找到了一个解决方案。看来是浏览器的问题。

试试这些:

希望对你有帮助

===

你并不孤单!我有使用 on... 事件(onReady 等)的代码,它在几天前工作,但突然停止工作,没有更改代码。

  • 它发布在 Google 问题跟踪器上(参见 here
  • 这里说明了同样的问题
  • 它甚至像 react-youtube 一样下降到 sub-libraries(参见 Issue #260

它似乎是从 9 月 9 日开始的,与 Youtube 数据 API 版本一致(参见 revision history for Sept. 9)。但是我在他们的列表中没有看到任何会损害 iframe events/functions

的东西

这就是我的进展,希望这能给某人一个提示以解决此问题。 ‍♂️ 将在发现时更新此评论。