Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make 'matches' URL of a Chrome Content Script Configurable

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

like image 720
grizzly Avatar asked Mar 15 '23 11:03

grizzly


2 Answers

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

like image 163
Zig Mandel Avatar answered Mar 23 '23 09:03

Zig Mandel


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
    }
};
like image 44
grizzly Avatar answered Mar 23 '23 09:03

grizzly