Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/438.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用Chrome扩展动态重新加载页面重新注入内容脚本_Javascript_Google Chrome_Google Chrome Extension - Fatal编程技术网

Javascript 使用Chrome扩展动态重新加载页面重新注入内容脚本

Javascript 使用Chrome扩展动态重新加载页面重新注入内容脚本,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,我有一个扩展,在更新选项卡时注入内容脚本。 主脚本: chrome.browserAction.onClicked.addListener(function(tab) { "use strict"; const sendScriptToPage = function(tabId, changeInfo, tab) { if (changeInfo.status === "complete" && tab && tab.url &am

我有一个扩展,在更新选项卡时注入内容脚本。 主脚本:

chrome.browserAction.onClicked.addListener(function(tab) {
    "use strict";
    const sendScriptToPage = function(tabId, changeInfo, tab) {
        if (changeInfo.status === "complete" && tab && tab.url && tab.url.indexOf("http") === 0) {
            console.log ("executeScript ");
            chrome.tabs.executeScript(tabId, {
                file: "content.js", allFrames: true
            });
        }
    };
    chrome.tabs.onUpdated.addListener(sendScriptToPage);
});
内容脚本:

const Content = (function() {
    "use strict";
    console.log("Content");
    const makeRandomColor = function(){
        let c = '';
        while (c.length < 6) {
            c += (Math.random()).toString(16).substr(-6).substr(-1)
        }
        return '#'+c;
    };
    document.body.style.backgroundColor = makeRandomColor();
}
)();
const Content=(函数(){
“严格使用”;
控制台日志(“内容”);
常量makeRandomColor=函数(){
设c='';
而(c.长度<6){
c+=(Math.random()).toString(16.substr(-6.substr(-1)
}
返回“#”+c;
};
document.body.style.backgroundColor=makeRandomColor();
}
)();
当我重新加载选项卡时,它工作正常。但是,当动态重新加载选项卡时,内容脚本会重新加载,尽管它已加载到选项卡中。这会显示在日志中,因为无法重新声明const

更新发生时不应该卸载内容脚本吗?如何知道内容脚本是否已加载

显示此行为的URL:

在搜索字段中键入内容会触发未更新的事件处理程序,但内容脚本已在页面中

测试扩展:

导航会擦除内容脚本,但更新的
会被许多事情触发

首先想到的是正在加载的iframe。主页不导航,但您可以不加选择地进行注入

可以采用多种方法:

  • 在执行任何操作之前,请检查是否定义了
    content
    ,以使内容脚本更加健壮
  • 收听不同的事件,例如各种
    webNavigation
    API事件。它们将唯一地标识所引用的帧
  • 不侦听事件-始终注入并更改触发逻辑(例如,在
    chrome.storage
    中保留一个标志)

  • 谢谢第一种方法似乎是最方便的。有趣的是,从这个问题中学习,并尝试将其应用于我的chrome扩展中的紧急事项,该扩展需要页面刷新才能正常工作?