【问题标题】:Firefox extensions: How to run function on every video change on YouTubeFirefox 扩展:如何在 YouTube 上的每个视频更改上运行功能
【发布时间】:2019-03-30 01:48:53
【问题描述】:

我有一个将js 代码注入 YouTube 页面的扩展程序。我在manifest.json 中使用了以下声明:

"content_scripts": [
    {
        "matches": [
            "*://*.youtube.com/*"
        ],
        "js": [
            "background.js"
        ]
    }
]

我想定义当我转到另一个视频时打印视频名称、喜欢和不喜欢的数量到控制台的函数。

我写在background.js:

window.onhashchange = function () {
    console.log(
        document.querySelector("h1.title > yt-formatted-string:nth-child(1)").innerHTML, "\n",
        document.querySelector("ytd-toggle-button-renderer.ytd-menu-renderer:nth-child(1) > a:nth-child(1) > yt-formatted-string:nth-child(2)").getAttribute("aria-label"), "\n",
        document.querySelector("ytd-toggle-button-renderer.style-scope:nth-child(2) > a:nth-child(1) > yt-formatted-string:nth-child(2)").getAttribute("aria-label"), "\n",
    )
}

但它只运行一次。如果我从“推荐”中选择新视频,它将不起作用。我也试过.onload.onunload

UPD:现在我发现的唯一方法是使用.setInterval

【问题讨论】:

    标签: javascript youtube firefox-addon-webextensions


    【解决方案1】:

    使用WebExtensions API 的几种可能的解决方案都需要一个后台脚本,该脚本将向您的内容脚本发送消息。修改您的 manifest.json 以包括:

    "background": {
        "scripts": ["background.js"]
    }
    

    我在这里命名了 background script background.js,这会与您当前拥有的内容发生冲突 - 您可能需要考虑将您的 content script 重命名为 contentscript.js,这样您就不会得到两个困惑。

    contentscript.js 中有消息监听器

    browser.runtime.onMessage.addListener(message => {
        if (message.videoChanged) {
            // do stuff
        }
    });
    

    使用tabs.onUpdated

    需要manifest.json 中的权限

    "permissions": [
        "tabs"
    ]
    

    background.js

    browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
        if (!changeInfo.url) {
            // url didn't change
            return;
        }
    
        const url = new URL(changeInfo.url);
        if (!url.href.startsWith('https://www.youtube.com/watch?') ||
            !url.searchParams.get('v')) {
            // not a youtube video
            return;
        }
    
        browser.tabs.sendMessage(tabId, {videoChanged: true});
    });
    

    此方法将在首次访问时向内容脚本发送消息,同时进行现场导航或自动播放。


    使用webNavigation.onHistoryStateUpdated

    需要manifest.json 中的权限

    "permissions": [
        "webNavigation"
    ]
    

    background.js

    browser.webNavigation.onHistoryStateUpdated.addListener(history => {
        const url = new URL(history.url);
        if (!url.searchParams.get('v')) {
            // not a video
            return;
        }
    
        browser.tabs.sendMessage(history.tabId, {videoChanged: true});
    },
        {url: [{urlMatches: '^https://www.youtube.com/watch\?'}]}
    );
    

    此方法在现场导航或自动播放时向内容脚本发送消息。


    使用webRequest.onBeforeRequestwebRequest.onCompleted

    当视频更改时,YouTube 会发出 xmlhttrequest。您可以通过打开开发者工具 (Ctrl+Shift+I) 来查看请求,选择网络选项卡,选择 XHR,按 watch? 过滤,然后让 YT 切换到下一个视频。您会看到下一个视频发生了两个请求,一个是在视频更改前不久在 URL 中带有 prefetch 参数的请求,另一个是在视频实际更改时没有 prefetch 参数。

    manifest.json 中的所需权限

    "permissions": [
        "https://www.youtube.com/watch?*",
        "webRequest"
    ]
    

    background.js

    browser.webRequest.onBeforeRequest.addListener(request => {
        const url = new URL(request.url);
        if (!url.searchParams.get('v') || url.searchParams.get('prefetch')) {
            // not a video or it's prefetch
            return;
        }
    
        browser.tabs.sendMessage(request.tabId, {videoChanged: true});
    },
        {urls: ['https://www.youtube.com/watch?*'], types: ['xmlhttprequest']}
    );
    

    onBeforeRequest 可能有点太快,并在新视频实际完成加载之前将消息发送到内容脚本。在这种情况下,您可以将其替换为 onCompleted

    此方法在现场导航或自动播放时向内容脚本发送消息。

    【讨论】:

      【解决方案2】:

      这个想法是找到一种定期检查 URL 更改的方法,所以我使用的技巧是利用用户点击播放/暂停按钮等内容的需要,当然还有其他要观看的视频。

      所以在您的页面内 onload 事件...(W 是您的 iframe ID)

       if(W.contentWindow.document.URL.indexOf('www.youtube.com/watch?v=')>-1){ // You may want to add some more permissable URL types here
      
         W.contentWindow.document.body.addEventListener('click',function(e){ CheckForURLChange(W.contentWindow.document.title,W.contentWindow.document.location); },false);
      
       }
      

      还有其他功能……

      function CheckForURLChange(Title,URL){
      
        // Your logic to test for URL change and take any required steps
      
       if(StoredURL!==URL){}
      
       }
      

      这不是最好的解决方案,但确实有效。

      【讨论】:

      • 这是一个不错的技巧,但如果您使用自动播放功能并且视频会自动更改,它将无法正常工作
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      • 2015-05-24
      • 1970-01-01
      • 2020-10-29
      • 2012-10-02
      相关资源
      最近更新 更多