Search code examples
javascriptgoogle-chromegoogle-chrome-extensioncontent-script

Dynamic loading of content script (chrome extension)


I have an chrome extension, with 2 content script injected by manifest and one background script.

{
    "manifest_version": 2,
    "name": "Test",
    "permissions": [
        "tabs", "<all_urls>", "activeTab", "storage" 
    ],

    "content_scripts": [
        {
            "matches": ["http://*/*", "https://*/*"],
            "js": [
                   "content/autofill/lib_generic.js",
                   "content/autofill/lib.js"],
            "run_at": "document_end"
        }
    ],

  "web_accessible_resources": [
        "content/specific_scripts/*"
    ],

    "background": {
        "scripts": ["background.js"],
        "persistent": false
    }

}

lib_generic.js contains one function named apply_forms(...) (its description is not important). The function is called from lib.js file. But this procedure doesn't work with several pages, so for each such page a I have a special script - also with only one function named apply_forms(...).

I have a function, which takes current domain as input and returns name of desired specific script or false if generic should be used.

There is too many files and it's logic is more complicated, so I can't just list all (url, script) pairs in "content_scripts" directive (I also don't want to inject all specific files as content script).

I've tried something like this in background (note that it's only for demonstration):

var url = ""; //url of current tab

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    if(changeInfo.status == "complete") {
        var filename = getSpecificFilename(url);
        chrome.tabs.executeScript(tabId, {file: filename}, function() {
            //script injected
        });
    }
});

NOTE: getSpecificFilename(...) will always return a name

But I get Unchecked runtime.lastError while running tabs.executeScript: Cannot access a chrome:// URL on the 5th line.

Can anyone help me with this? Is it the good way to "override` function definition dynamically, or should I go different way (which one, then).

Thanks.


Solution

  • This means, probably, that you're getting an onUpdated event on an extension/internals page (popup? options page? detached dev tools?).

    One option is to filter by URL:

    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
        if(changeInfo.status == "complete") {
            if(!tab.url.match(/^http/)) { return; } // Wrong scheme
            var filename = getSpecificFilename(url);
            chrome.tabs.executeScript(tabId, {file: filename}, function() {
                //script injected
            });
        }
    });
    

    Another (and probably better) option is to make your content script request this injection:

    // content script
    chrome.runtime.sendMessage({injectSpecific : true}, function(response) {
      // Script injected, we can proceed
      if(response.done) { apply_forms(/*...*/); }
      else { /* error handling */ }
    });
    
    // background script
    chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
      if(message.injectSpecific){
        var filename = getSpecificFilename(sender.url);
        chrome.tabs.executeScript(sender.tab.id, {file: filename}, function() {
          sendResponse({ done: true });
        });
        return true; // Required for async sendResponse()
      }
    });
    

    This way you know that a content script is injected and initiated this.