I'm writing a Chrome extension so I need to be able to listen for changes in the YouTube URL (i.e., see that you switched videos). YouTube makes this hard because with its HTML5 video player there is no full page reload, there is no URL fragment change (cannot listen for hashchange event as other answers have suggested). Listening for pushState also doesn't work. I've spent a lot of time looking for answers here on SO and all the ones I've seen thus far (except for one -- that I really don't want to use) don't work.
The only answer I've seen that works is setting a timeout to run every second to see if the URL changed (ugly!).
Edit: The possible duplicate question is a totally different question--one dealing with listening to URL changes the other dealing with getting the extension to load.
Question: How can I detect URL changes in YouTube's HTML5 video player without polling?
My solution was to simply check for the transitionend
event on the #progress
element (this is the red progress bar that shows up at the top).
document.addEventListener('transitionend', function(e) {
if (e.target.id === 'progress')
// do stuff
});
An even cleaner solution is to just listen for the spfdone
event triggered by spfjs
, the framework used by YouTube to manipulate push state. Credit to Rob for the answer.
document.addEventListener('spfdone', function() {
// do stuff
});
I stumbled across this issue, so maybe this will benefit someone.
What did the trick for me is to listen for the yt-page-data-updated
event, which detects a video switch.
I was able to inspect it by using the monitorEvents(document.body)
and getEventListeners(document.body)
Chrome DevTools Commands upon page update. But keep in mind that it won't work on full page reload (by directly accessing the URL), so I had to coordinate with a load
event, something like this:
window.addEventListener('load', function () {
console.log('load');
});
window.addEventListener('yt-page-data-updated', function () {
console.log('url change');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With