Reputation: 2978
So I'm trying to follow the instructions for a firefox extension using WebExtensions and I want to attach a content script to certain pages (as discussed here: https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Modify_a_web_page ).
Problem is I don't want to specify the set of pages I want the content_script to run on in manifest.json when I write the extension but load it from local storage, i.e., I have an options page set up where the user can specify the pages the content script should be run on. Is it possible to dynamically change the list of pages to be modified that is normally set using the content_script directive in manifest.json?
Thanks
Upvotes: 2
Views: 1523
Reputation: 2040
How about that? There is a bunch of events to listen, you can pick any one which would satisfy uour requirements:
The documentation is here. And this is an example of how to make red background on subdomains of example.com
. Of course, you can build the list of URL filters dynamically, this is just a PoC:
browser.webNavigation.onCommitted.addListener(
function(details) {
browser.tabs.insertCSS(details.tabId, {code: 'body {background:red}'})
},
{url: [{hostSuffix: '.example.com'}]}
);
Upvotes: 0
Reputation: 33296
No, there is no way to modify the URLs into which injection will occur for a manifest.json
content_script
(either CSS or JavaScript). The specified code will be injected in all matching URLs. This is for multiple reasons.
One of the reasons this is not possible is security/transparency to the user. The manifest.json explicitly declares which URLs your content script will be modifying, states that it will be modifying the active tab, or that it will have access all URLs/tabs. If you were permitted to change the URLs, then you would effectively be given the ability to access all URLs without explicitly declaring that you are doing so.
Yes, it would be possible to have a way to declare that you are going to do so. Chrome has an experimental way to do so with chrome.declarativeContent
. In Chrome this is considered experimental, even after being available for a couple/few years. It is not available in Firefox. When it will be available, or even if it will be available in Firefox is unclear. In addition, even in Chrome, it lacks some features available to other methods of injecting scripts (e.g. run_at
/runAt
).
In order to have complete control over injecting, or not injecting, you will need to perform the injection via tabs.insertCSS()
and/or tabs.executeScript()
. Injecting, or not injecting, scripts and CSS with these methods is fully under the control of the JavaScript in your extension. It is possible to get similar functionality using these methods to what you obtain with manifest.json
content_script
entries, but with more control. This greater control comes at the expense of greater complexity.
Upvotes: 2