JavaScript to listen for URL changes in YouTube HTML5 Player

前端 未结 3 1644
面向向阳花
面向向阳花 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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?
    });
    

提交回复
热议问题