首页 > 解决方案 > YouTube 播放器 API 未按文档说明工作

问题描述

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 来监控这里的问题。此示例的大部分内容是官方文档中示例之一的直接副本。

标签: javascriptapiyoutube

解决方案


[编辑] 从此Google 问题跟踪器中找到了解决方案。好像是浏览器的问题。

试试那些:

希望有帮助

===

你不是一个人!我有使用几天前工作的on...事件(等)的代码,突然停止工作而没有代码更改。onReady

看起来它开始于 9 月 9 日,与 Youtube Data API 版本一致(请参阅9 月 9 日的修订历史)。但我在他们的列表中看不到任何会损害 iframe 事件/功能的内容

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


推荐阅读