本文介绍了Chrome 扩展程序 - 页面更新两次,然后在 YouTube 上删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个小扩展,将一个简单的 html 注入视频正下方的 YouTube 页面.如果我简单地访问 youtube 网址,它就可以正常工作.但是,如果我从 youtube 提供的视频中选择视频,那么我的 html 代码会被注入两次但被删除.我可以看到它几乎立即出现然后消失.

I want to make a small extension that injects a simple html into a YouTube page right under the video. It works fine if I simple visiting a youtube url. However if I choose a video from youtube offers then my html code is injected twice but removed. I can see that it to appear and then disappear almost immediately.

我的代码是:

background.js

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {

    if ( changeInfo.status == 'complete' && tab.status == 'complete' && tab.url != undefined ) {

        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            chrome.tabs.sendMessage(tabs[0].id, {method: "reDraw"}, function(response) {
                console.log("Injection ready!");
            });
        });

    }

});

content.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        if (request.method == "reDraw") {
            $.get(chrome.extension.getURL('/mytest.html'), function(data) {
                $(data).insertAfter('#placeholder-player');
            });
        }
    }
);

推荐答案

chrome.tabs.onUpdated 也会为 iframes 触发,对于 youtube 来说,有很多 iframes 会触发这个事件,除此之外,当您从一个视频转到另一个视频时,youtube 不会重新加载页面.有关 youtube 问题的更多详细信息,您可以查看以下线程:

chrome.tabs.onUpdated will also fire for iframes, and for youtube, there are many iframes will trigger this event, besides that, youtube doesn't reload the page when you go from one video to another. For more details about youtube issue, you could take a look at these threads:

考虑到您正在检测 youtube 视频页面,我建议您使用 chrome.webNavigation.onHistoryStateUpdated

Considering you are detecting youtube video page, I would suggest you used chrome.webNavigation.onHistoryStateUpdated

// To handle youtube video page
chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) {
    if(details.frameId === 0) {
        // Fires only when details.url === currentTab.url
        chrome.tabs.get(details.tabId, function(tab) {
            if(tab.url === details.url) {
                console.log("onHistoryStateUpdated");
            }
        });
    }
});

这篇关于Chrome 扩展程序 - 页面更新两次,然后在 YouTube 上删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 02:37