JavaScript to listen for URL changes in YouTube HTML5 Player

前端 未结 3 1628
面向向阳花
面向向阳花 2020-12-30 12:02

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

相关标签:
3条回答
  • 2020-12-30 12:23

    I'm not entirely sure how this would work from a chrome extension, but if it's feasible the onStateChange event could be of great benefit to you. I'm fairly 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's within the same element.
        console.log(player.getVideoUrl());
      }
      // Watch for other events?
    });
    
    0 讨论(0)
  • 2020-12-30 12:25

    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
    });
    


    Update:

    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
    });
    
    0 讨论(0)
  • 2020-12-30 12:38

    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');
    });
    
    0 讨论(0)
提交回复
热议问题