Reputation: 3788
I'm making a very simple Chrome extension to block requests to some domains (got tired of slow page loads on many websites, waiting on facebook junk). My question is about how to efficiently load a user-specified list of domains. The Chrome documentation points out that it is more efficient to pass a map containing 'urls' to the addListener call instead of passing in all requests and checking them in my function. How can I do that, but use a user-provided list of domains/expressions?
Here are my manifest and js files so far:
Manifest.json
{
"name": "I Don't Want YOur Social Networking Junk",
"version": "1.0",
"description": "This extension let's you block (Chrome will not download) content from domains. Too many sites slow themselves down by bringing in a bunch of junk from sites like facebook. This will let you block those things.",
"permissions": ["webRequest", "webRequestBlocking", "http://*/*", "https://*/*"],
"background": {
"scripts": ["background.js"]
},
"manifest_version": 2
}
background.js
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
return {cancel: true};
}, { urls: ["*://*.facebook.com/*", "*://*.facebook.net/*"] }, ["blocking"]);
As you can see I have a couple of hard-coded expressions in the urls list for now. That's what I'd like to load from something that a user could populate. Recommendations?
Upvotes: 10
Views: 5569
Reputation: 4162
Use something like this:
function blockRequest(details) {
return {cancel: true};
}
function updateFilters(urls) {
if(chrome.webRequest.onBeforeRequest.hasListener(blockRequest))
chrome.webRequest.onBeforeRequest.removeListener(blockRequest);
chrome.webRequest.onBeforeRequest.addListener(blockRequest, {urls: urls}, ['blocking']);
}
You can provide an options page to let the user to specify domains to block (and preferably save them with chrome.storage API). In your background page, update filters by re-registering the listener when it is initialized or the setting is changed.
By the way, you should use the Declarative Web Request API when it is stable since it is much more efficient and doesn't require a persistent background page.
Upvotes: 11