JavaScript to listen for URL changes in YouTube HTML5 Player

I am writing a Chrome extension, so I need to be able to listen to the changes in the YouTube URL (i.e. see that you have switched the video). YouTube makes this difficult because with its HTML5 video player there is no full page reload, no change to the URL fragment (it is impossible to listen to the hashchange event as other answers suggested ). Listening to pushState also does not work. I spent a lot of time searching for answers here on SO, and all the ones that I have seen so far (except for one - which I really do not want to use) do not work.

The only answer I've seen works is setting a timeout to run every second to see if the URL has changed (ugly!).

Edit: A possible duplicate question is a completely different question: one of the questions related to listening to URLs, the other related to downloading the extension.

Question: How can I detect URL changes in a YouTube video player with HTML5 without polling?

+5
source share
3 answers

My solution was to simply test the transitionend event on the #progress element (this is the red progress bar that appears at the top).

 document.addEventListener('transitionend', function(e) { if (e.target.id === 'progress') // do stuff }); 


Update:

An even cleaner solution is to simply listen to the spfdone event spfdone by spfjs , the platform that YouTube uses to manage push status. Credit to Rob for the answer .

 document.addEventListener('spfdone', function() { // do stuff }); 
+7
source

I'm not quite sure how this will work with the chrome extension, but if possible, the onStateChange event can be of great benefit to you. I am new to the YouTube API, but this works for me:

 var player = document.getElementById('youtubeVideo'); player.addEventListener('onStateChange', function(e) { if (e.data === 1) { // Video started playing. // Should work for when the video changes as well. // As long as it within the same element. console.log(player.getVideoUrl()); } // Watch for other events? }); 
+1
source

I came across this problem, so maybe this is useful to someone. What suited me was listening to the yt-page-data-updated event, which detects a video switch.

I was able to verify this with monitorEvents(document.body) Chrome DevTools monitorEvents(document.body) and getEventListeners(document.body) when refreshing the page. But keep in mind that it will not work when the page is completely reloaded (by directly accessing the URL), so I had to coordinate with the load event something like this:

 window.addEventListener('load', function () { console.log('load'); }); window.addEventListener('yt-page-data-updated', function () { console.log('url change'); }); 
0
source

Source: https://habr.com/ru/post/1014578/


All Articles