YouTube Iframe API - OnStateChange suddenly not wo

2020-07-09 09:48发布

Until around 6pm EST this code below would have worked fine, but now for some reason onStateChange is not firing. I've tried on multiple browsers and have had friends check it. See anything obviously wrong?

<div id="video">
  <div id="player_wrap">
    <div id="player"></div>
  </div>
</div>

   <script>

    var tag = document.createElement("script");
    tag.src = "http://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName("script")[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    function onYouTubeIframeAPIReady() {
    var player;

        player = new YT.Player("player", {
          width: 640,
          height: 400,
          videoId: "MbfsFR0s-_A",
          events: { 
            'onReady': onPlayerReady, 
            'onStateChange': onPlayerStateChange          
          }
        });
      }

function onPlayerReady() {

alert ("player ready"); 

}


function onPlayerStateChange(event) {

alert ("something happened"); 

}

标签: youtube-api
2条回答
ゆ 、 Hurt°
2楼-- · 2020-07-09 10:31

This is a temporary issue with the iFrame Player API. You can read about it here: https://code.google.com/p/gdata-issues/issues/detail?id=4706

Jeff Posnick posted a temporary workaround here: http://jsfiddle.net/jeffposnick/yhWsG/3/

Basically, you just need to add the event listener within the onReady event (just a temporary fix):

function onReady() {
    player.addEventListener('onStateChange', function(e) {
        console.log('State is:', e.data);
    });
}
查看更多
放荡不羁爱自由
3楼-- · 2020-07-09 10:55

The solution posted here works fine and is REALLY clean:

player = new YT.Player(element,{
    events: {
        onReady: function(){
            /*
            Do your stuff
            */
            // Attach a void function to the event
            player.addEventListener('onStateChange',function(){});
        },
        onStateChange: function(){
        // Actual function that gets executed during the event
        }
    }
});
查看更多
登录 后发表回答