YouTube onPlayerReady is never triggered

2020-04-21 06:06发布

Any idea why this script doesn't work? All I want is to track onStateChanged event, but that is never called either.

When I open the html document with below code, I have no errors, the youtube script loads just fine, the player object is not undefined, looks fine too.

$(document).ready(function(){
    loadScript();
});

    function loadScript() {
        var tag = document.createElement('script');
        tag.src = "https://www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    }

    var player;
    function onYouTubeIframeAPIReady() {
      player = new YT.Player('player', {
        events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
      });
      alert(player);
    }

    var done = false;
    function onPlayerStateChange(event) {
          alert('state changed');
        if (event.data == YT.PlayerState.PLAYING && !done) {
          setTimeout(stopVideo, 3000);
          done = true;
        }
    }
    function stopVideo() {
        player.stopVideo();
    }
    function onPlayerReady(event) {
        event.target.playVideo();
    }

My iframe:

<iframe id="player width="400" height="300" src="https://www.youtube.com/embed/j0pJekWgeFE" frameborder="0" allowfullscreen></iframe>

See fiddle: https://jsfiddle.net/rg2uy1f8/

1条回答
The star\"
2楼-- · 2020-04-21 06:38

I found an answer here: How do I get the reference to an existing YouTube player?

The reason my solution didn't work, was that my iframe was missing an attribute: enablejsapi="1" and also I was missing: ?enablejsapi=1 in YouTube video url.

You may find the working solution here: http://jsfiddle.net/bf7zQ/2/

查看更多
登录 后发表回答