Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 300
dakov Avatar asked Sep 08 '14 14:09

dakov


People also ask

What is Content_scripts?

A content script is a part of your extension that runs in the context of a particular web page (as opposed to background scripts which are part of the extension, or scripts which are part of the website itself, such as those loaded using the <script> element).

Can content scripts access chrome storage?

User data can be automatically synced with Chrome sync (using storage. sync ). Your extension's content scripts can directly access user data without the need for a background page.

What is content scripts in Manifest JSON?

Content scripts are files that run in the context of web pages. By using the standard Document Object Model (DOM), they are able to read details of the web pages the browser visits, make changes to them, and pass information to their parent extension.

Could not load JavaScript JS content JS for content script?

It means there's no content. js in the same folder as manifest. json or you didn't reload the extension on chrome://extensions page or you're looking at an old error that's no longer applicable.


1 Answers

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.

like image 121
Xan Avatar answered Sep 25 '22 13:09

Xan