Andrey Shchekin
Andrey Shchekin

Reputation: 21599

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;

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

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

However, this seems to inject my content script twice in some cases (it might happen when enhance.js does window.history.pushState).

How can I fInd out whether the tab already has my content script? I tried chrome.tabs.sendRequest but it never called the callback if the content script was not yet added.

Upvotes: 11

Views: 8212

Answers (1)

Adam Ayres
Adam Ayres

Reputation: 8900

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

Upvotes: 11

Related Questions