Chrome Extension: how to detect that content script is already loaded into a tab?

后端 未结 1 1032
野性不改
野性不改 2021-01-31 12:23

I have the following code in my background script:

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


        
相关标签:
1条回答
  • 2021-01-31 12:55

    EDIT: Updated per first comment on this answer.

    You might try something like this. Add a onRequest listener that will be used as a callback to load the scripts you want, but they will only load based on a value sent as part of the request message. Then use executeScript to call "code" directly that sends a message with the value of a global variable (if it exists).

    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;" });
                });
            });
         }
    });
    
    0 讨论(0)
提交回复
热议问题