问题
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