使用注入的 javascript 检测 Youtube 视频变化 [英] Detect Youtube video change with injected javascript

查看:28
本文介绍了使用注入的 javascript 检测 Youtube 视频变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个扩展(一些注入的 js),它向 youtube 页面添加了一些按钮,效果很好.我的问题是,当用户点击另一个视频(比如在右侧列表中)时,下一个视频会在没有实际页面重新加载的情况下加载.有什么方法可以检测到这种变化,以便我可以重新运行我的代码?

I am building an extension (some injected js) that adds some buttons to a youtube page, which works fine. My issue is that when a user clicks on another video (say in the right hand side list), the next video is loaded without an actual page reload. Is there any way to detect this change so that I can rerun my code?

我已经尝试过诸如绑定到 hashchange 事件之类的事情,但无济于事.

I have already tried things like binding to the hashchange event, to no avail.

推荐答案

想法很简单:

  • 使用 background.js 使用 chrome.tabs.onUpdated
  • 侦听对特定 youtube 标签页的 url 更改
  • 检测到标签更改后,将新 URL 发送到在该标签中运行的内容脚本

后台页面也会侦听其他标签的 URL 更改,但我很确定您可以找出解决方法.

The background page listens for URL changes to other tabs also but I'm pretty sure you can figure out how to fix that.

ma​​nifest.json

{
    "manifest_version": 2,
    "name": "Tab url change detection",
    "version": "1.0",
    "background": {
        "persistent":true,
        "page":"bg.html"
    },
    "content_scripts": [{
            "matches": ["http://www.youtube.com/*"],
            "js": ["app.js"]
        }
    ],
    "permissions": [
        "tabs",
        "http://www.youtube.com/*"
    ]
}

background.html

<script src="background.js"></script>

background.js

//Listen for when a Tab changes state
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
    if(changeInfo && changeInfo.status == "complete"){
        console.log("Tab updated: " + tab.url);

        chrome.tabs.sendMessage(tabId, {data: tab}, function(response) {
            console.log(response);
        });

    }
});

app.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    //here we get the new 
    console.log("URL CHANGED: " + request.data.url);
});

这篇关于使用注入的 javascript 检测 Youtube 视频变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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