Chrome extension: load different content scripts Chrome extension: load different content scripts google-chrome google-chrome

Chrome extension: load different content scripts


Just in the interest of completeness, the way you'd do this from the manifest is to have as many matches blocks under "content_scripts" as needed:

"content_scripts": [  {    "matches": ["http://www.google.com/*"],    "css": ["mygooglestyles.css"],    "js": ["jquery.js", "mygooglescript.js"]  },  {    "matches": ["http://www.yahoo.com/*"],    "css": ["myyahoostyles.css"],    "js": ["jquery.js", "myyahooscript.js"]  }],


Rather than using content scripts that are bound to URL expressions specified in the manifest, you should use executeScript, which lets you programmatically decide when to inject a JS snippet or file:

// background.jschrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {  // there are other status stages you may prefer to inject after  if (changeInfo.status === "complete") {    const url = new URL(tab.url);    if (url.hostname === "www.stackoverflow.com") {          // this is the line which injects the script      chrome.tabs.executeScript(tabId, {file: "content_script.js"});    }  }});

Make sure to add tabs permission to manifest.json:

{  // ...settings omitted...  "permissions": [    "tabs",  // add me  ]}


you should use Programmatic injection

chrome.tabs.executeScript(null, {file: "content_script.js"});