Skip to content Skip to sidebar Skip to footer

Chrome Extension: How To Detect That Content Script Is Already Loaded Into A Tab?

I have the following code in my background script: chrome.tabs.onUpdated.addListener(function(tabId, changeinfo, tab) { if (changeinfo.status !== 'complete') return;

Solution 1:

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;" });
            });
        });
     }
});

Post a Comment for "Chrome Extension: How To Detect That Content Script Is Already Loaded Into A Tab?"