A API do player do YouTube não está funcionando conforme documentado

Sep 16 2020

Parece que a API do player do YouTube não está funcionando no momento. O player inicializará corretamente, mas nenhum dos métodos ou eventos está funcionando.

<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>

Criei um codepen simples para monitorar o problema aqui . A maior parte deste exemplo é uma cópia direta de um dos exemplos nos documentos oficiais .

Respostas

5 KimChouard Sep 17 2020 at 05:36

[EDIT] Encontrou uma solução neste rastreador de problemas do Google . Parece que é um problema do navegador.

Experimente aqueles:

Espero que ajude 🙃

===

Você não está sozinho! Eu tenho código usando os on...eventos ( onReady, etc), que funcionou há alguns dias e de repente parou de funcionar sem nenhuma alteração de código.

  • Ele foi postado no Google Issue Tracker (veja aqui )
  • Aqui está outra postagem stackoverflow afirmando o mesmo problema
  • Chegou até mesmo a sub-bibliotecas como react-youtube(consulte a edição 260 )

Parece que começou em 9 de setembro, o que se alinha com uma versão da API de dados do YouTube (consulte o histórico de revisão de 9 de setembro ). Mas não vejo nada na lista que comprometa os eventos / funções do iframe 🤔

Foi assim que eu cheguei, espero que isso dê uma dica para alguém chegar a uma resolução disso. 🤷🏼‍♂️ Atualizará este comentário conforme surgirem as descobertas.