Reputation: 930
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
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:
getEventListeners(document)
in the console (also works with window
and any DOM element)ev
or event
bubble to the right of <html>
and other tagsUpvotes: 1