I'm looking for a way how to make Chrome Content Script match URL configurable.
Usually the URL for the script is specified in manifest.json
within matches
array. I believe I can set it to http://*/
or https://*/
and check/filter the execution at the beginning of the script for the required URL, but I was wondering if there is a cleaner way how to do this.
Is there a way how to run the script for the configured URL, without being run at all if the URL doesn't match?
Thanks
this is possible. take a look at optional permissions. its configuration is explained in the official docs.
in short, you ask for all urls in optional permissions, and then the user can add more domains and chrome remembers each aproval.
when the user performs a user action (like pressing an OK button after typing the new domain) make a chrome api call to request the permission. if it already has it, permission isnt asked again. Else chrome will display a modal chrome dialog asking the user to approve the new permission.
I was going to continue explaining options but I found this other s.o. answer which explains well the options you have. https://stackoverflow.com/a/26677279/2213940
Thanks for the suggestions, but I ended up using Programmatic Injection of the scripts (more here: Chrome Developer: Programmatic Injection.
Following the documentation, I added two permissions into manifest.json
: tabs
and a generic http://*/
to access any domain the user might want.
Then created a background script that checks for the URL of the tab if it changes, and if it matches the setting stored in chrome.settings
set by the user, it injects the requested script.
That way only the check is being done without the script actually loading into memory.
Here is a part of manifest.json
:
"permissions": [
"tabs",
"http://*/", "https://*/"
],
"background": {
"scripts": [ "background.js" ],
"persistent": false
},
Script injection:
// inject the script
chrome.tabs.executeScript(tabId, {
file: 'script.js',
runAt: 'document_end'
});
EDIT
Check for the requested URL:
// var url = ''; // get URL from chrome.settings
// attach a listener
chrome.tabs.onUpdated.addListener(tabUpdated);
// check that the url starts with the saved one
var tabUpdated = function (tabId, changeInfo, tab) {
if (tab.url.indexOf(url) === 0) {
// run the script
}
};
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