thairish
thairish

Reputation: 1043

YouTube API - events on a embedded iframe not working

I am trying to get a "pause" event with the YouTube API on a YouTube video created by AMP (Accelerated Mobile Pages) with this basic example: https://ampbyexample.com/components/amp-youtube/

The code works and I get a video showing. The next thing I wanted to do was do something when the video is paused. I've had a look on how to do this and I've got the current code:

//The iframe generated from AMP does not give an ID so I have added one
$('#AMP_1 iframe').attr('id', 'yt_player');

//Load API code
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('yt_player', {
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}

function onPlayerReady() {
  console.log("READY");
}

function onPlayerStateChange() {
  console.log("STATE CHANGE");
}

When I run this I am not getting console errors and none of the console.log calls are displaying anything. The player variable stays undefined.

The iframe produced by AMP does have "enablejsapi=1" in the URL.

Do I need to do anything/am I missing something, to get the pause event on the video?

Upvotes: 0

Views: 860

Answers (1)

Hakan Kose
Hakan Kose

Reputation: 1656

You need to have a parameter on function onPlayerStateChange to get the event data.

function onPlayerStateChange(event) {
    switch(event.data){
        case 2:
            console.log("PAUSE!")
            break;
    }
}

other event.data list

  • -1 (unstarted)
  • 0 (ended)
  • 1 (playing)
  • 2 (paused)
  • 3 (buffering)
  • 5 (video cued).

Upvotes: 1

Related Questions