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

烂漫一生 提交于 2019-12-23 00:44:11

问题


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)?


回答1:


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


来源:https://stackoverflow.com/questions/41423290/can-i-use-an-external-array-to-match-urls-for-content-script-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!