Shane_IL
Shane_IL

Reputation: 345

Can I use an external array to match URLs for content script injection?

I'm working on a chrome extension where I'd like to inject a content script into a list of urls. Usually I'd use the regular syntax:

{
  "name": "My extension",
  ...
  "content_scripts": [
    {
      "matches": ["http://www.google.com/*"],
      "css": ["mystyles.css"],
      "js": ["jquery.js", "myscript.js"]
    }
  ],
  ...
}

But for the match patterns I'd like to pull the array from a server. Is there a way to programmatically set the "matches" array (from the background.js file for example)?

Upvotes: 4

Views: 1074

Answers (1)

Iván Nokonoko
Iván Nokonoko

Reputation: 5118

As far as I know, you cannot modify your manifest.json file from within the extension. What you can do is programmatically inject your content scripts from the background page when the tab's URL matches one of the URLs you've got from the server.

Note that you will need tabs and <all_urls> permissions.

background.js

var list_of_URLs; //you populate this array using AJAX, for instance.

populate_list_of_URLs();

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
    if (list_of_URLs.indexOf(tab.url) != -1){
        chrome.tabs.executeScript(tabId,{file:"jquery.js"},function(){
            chrome.tabs.executeScript(tabId,{file:"myscript.js"});
        });
    }
});

Upvotes: 3

Related Questions