I want to load a different content script depending on the page and tab that is currently selected. Right now, I have three content scripts. I want to use two of them for one page and the third one for another page.
Belonging to page 1:
content_script.js
load_content_script.js
Belonging to page2:
newtab_content_script.js
right now my manifest looks like this
{ "name": "A plugin for AdData express. Generate an instant excel document from the brands you check mark.", "version": "1.0", "background_page": "background.html", "permissions": [ "cookies", "tabs", "http://*/*", "https://", "*", "http://*/*", "https://*/*", "http://www.addataexpress.com", "http://www.addataexpress.com/*" ], "content_scripts": [ { "matches": ["<all_urls>","http://*/*","https://*/*"], "js": ["load_content_script.js", "content_script.js", "newtab_content_script.js", "jquery.min.js", "json.js"] } ], "browser_action": { "name": "AdData Express Plugin", "default_icon": "icon.png", "js": "jquery.min.js", "popup": "popup.html" } }
how would I structure this in the manifest or elsewhere?
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).
In addition to sending messages between different components in your extension, you can use the messaging API to communicate with other extensions.
Using web_accessible_resources This prevents websites from fingerprinting a browser by examining the extensions it has installed. Note: In Chrome in Manifest V2, an extension's ID is fixed.
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.js chrome.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 ] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With