okram
okram

Reputation: 930

How can I detect that YouTube has finished video playback from injected script (using chrome extension)?

I'm trying to make Chrome extension that invokes my function when video on watch page (like 'www.youtube.com/watch?=xxxxxxxx') finishes playback. I want to do that using an injected script. Currently I'm using setInterval to check if video.ended==true but I would like to find a way to work without intervals and just use some event listener ideally.

I tried to add onended event listener to #movie_player and video elements, but that does not work. I also tried to listen to readystatechange event but this one does not fire either. Adding onplay and onplaying event listeners to #movie_player doesn't fire as well.

Is there any way to do what I want to without using intervals?

Upvotes: 2

Views: 929

Answers (1)

woxxom
woxxom

Reputation: 73736

Use ended DOM event on the video element:

var videoElement = document.querySelector('video');
videoElement.addEventListener('ended', function(event) {
  console.log(event);
});

Note, Youtube site uses AJAX navigation, which means your extension's content script runs only one time when the site is opened in any given tab. Add a listener for yt-navigate-finish to detect such navigation:

document.addEventListener('yt-navigate-finish', function(event) {
  var videoElement = document.querySelector('video');
  videoElement.addEventListener('ended', function(event) {
    console.log(event);
  });
});

Use devtools to see more events used by the page:

  • in Chrome: open Elements inspector and switch to the "Event listeners" subpanel
    or type getEventListeners(document) in the console (also works with window and any DOM element)
  • in Firefox: open Inspector and click the ev or event bubble to the right of <html> and other tags

Upvotes: 1

Related Questions