JavaScript来监听YouTube HTML5播放器中的URL更改 [英] JavaScript to listen for URL changes in YouTube HTML5 Player

查看:174
本文介绍了JavaScript来监听YouTube HTML5播放器中的URL更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在撰写Chrome扩展程序,因此我需要能够监听YouTube网址中的更改(即查看您切换的视频)。 YouTube使这很难,因为HTML5视频播放器没有完整页面重新加载,没有更改URL片段(无法监听hashchange事件其他答案建议)。收听 pushState 也不起作用。我花了很多时间在这里寻找答案,迄今为止我所见过的所有答案(除了一个 - 我真的不想使用)不起作用。



我见过的唯一答案就是设置超时运行,每秒运行一次以查看URL是否更改(丑陋!)。



编辑:可能重复的问题是一个完全不同的问题 - 一个处理监听URL变化,另一个处理获取扩展加载。



问题:如何检测YouTube中的URL更改没有投票的HTML5视频播放器?

解决方案

我的解决方案是只检查 transitionend #progress 元素上的$ c>事件(这是显示在顶部的红色进度条)。

  document.addEventListener(过渡结束',函数(e){
if(e.target.id ==='progress')
// do stuff
});




更新:



一个更清晰的解决方案是只监听 spfjs触发的 spfdone 事件,这是YouTube用来操纵推送状态的框架。 向Rob表示感谢答案

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


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


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

这篇关于JavaScript来监听YouTube HTML5播放器中的URL更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆