Chrome扩展程序:如何检测内容脚本是否已加载到选项卡中?

And*_*kin 11 javascript google-chrome-extension

我的后台脚本中有以下代码:

chrome.tabs.onUpdated.addListener(function(tabId, changeinfo, tab) {
    if (changeinfo.status !== 'complete')
        return;

    if (!matchesUrlFilters(tab.url))
        return;

    chrome.tabs.executeScript(tabId, { file: "jquery-1.7.1.min.js" }, function() {
        chrome.tabs.executeScript(tabId, { file: "enhance.js" });
    });
});
Run Code Online (Sandbox Code Playgroud)

然而,这似乎两次注入我的内容脚本在某些情况下(可能会发生enhance.jswindow.history.pushState).

如何确定选项卡是否已包含我的内容脚本?我试过chrome.tabs.sendRequest但是如果还没有添加内容脚本,它从不调用回调.

Ada*_*res 10

编辑:更新了这个答案的第一个评论.

你可能会尝试这样的事情.添加一个onRequest侦听器,该侦听器将用作回调以加载所需的脚本,但它们只会根据作为请求消息的一部分发送的值进行加载.然后使用executeScript直接调用"代码",发送带有全局变量值(如果存在)的消息.

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

    // execute a content script that immediately sends back a message 
    // that checks for the value of a global variable which is set when
    // the library has been loaded
    chrome.tabs.executeScript(tabId, {
        code: "chrome.extension.sendRequest({ loaded: EnhanceLibIsLoaded || false });"
    });

    ...
});

// listen for requests
chrome.extension.onRequest.addListener(function(req, sender, sendResponse) {
    if (req.loaded === false) {
        chrome.tabs.executeScript(tabId, { file: "jquery-1.7.1.min.js" }, function() {
            chrome.tabs.executeScript(tabId, { file: "enhance.js" }, function() {
                // set the global variable that the scripts have been loaded
                // this could also be set as part of the enhance.js lib
                chrome.tabs.executeScript(tabId, { code: "var EnhanceLibIsLoaded = true;" });
            });
        });
     }
});
Run Code Online (Sandbox Code Playgroud)

  • 我想使用它,但控制台中有一个错误说:`Uncaught ReferenceError: EnhanceLibIsLoaded is not defined` :( (2认同)