0
votes

I have a training program where I'm trying to display a YouTube video in an iFrame, automatically play it, and advance to the next page when the video completes. I can get the onYouTubeIframeAPIReady function to fire, but none of the other events will. Actually, I'm only interested in state change.

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

...

    //function onYouTubeIframeAPIReady() {  //tried this too but no change
    window.onYouTubeIframeAPIReady = function() {
        player = new YT.Player('externalComponent', {
        events: {
            'onReady': onPlayerReady,
            'onError': onPlayerError,
            'onStateChange': onPlayerStateChange
            }
        });
        console.log('api ready');
    }

    function onPlayerStateChange(event) {
        console.log('onStateChange');
        console.log(YT.PlayerState);
    }

When it runs, you can see "api ready" in the console but nothing else. iFrame looks like:

    <iframe id="externalComponent" src="https://youtube.com/embed/_S_Bg9qfa8o?enablejsapi=1&controls=0&autoplay=1" width="1024" height="576" allow="autoplay" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>

What is stopping onStateChange from working and not automatically playing? The controls do not show.

1
It should work. Find below the working jsfiddle jsfiddle.net/0oe9wqmhMohamed Yaseen

1 Answers

0
votes

I was unable to get it to work as I've posted. I had to change the code to use a div rather than an iframe, add a video ID and other parameters in the playerVars. Once I did that, the video played automatically, showed no controls, and fired the state change event.

  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      playerVars: {
                autoplay: 1,
                controls: 0,
                showinfo: 0,
                autohide: 1
                },
      videoId: '_S_Bg9qfa8o',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

...

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