I am trying to make a Chrome extension that blocks URLs with a specific word in the subdomain, but not other URLs in that domain. For example, let's say I want to block all tumblr blogs with the word "cola" in the subdomain.
It should be able to block this page: http://coca-cola.tumblr.com/.
I have tried to use this url match: urls:["*://*cola*.tumblr.com/*"]
, but it is not working. And I cannot think of any other combinations that might work. Can somebody point me in the right direction?
This is my full background.js:
chrome.webRequest.onBeforeRequest.addListener(
function() {
return {cancel: true };
},
{
urls:["*://*cola*.tumblr.com/*"] // This is the part I'm messing up.
},
["blocking"]
);
Your code fails because *://*cola*.tumblr.com/*
is not a valid match pattern. Wildcards can only be used in the path component of an URL, or at the start of a host name.
If you want to block an URL whose subdomain contains some keyword, you need to match the whole domain, and use JavaScript to check whether the subdomain contains the profane word.
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
var hostname = details.url.split('/', 3)[2];
return {
cancel: hostname.indexOf('cola') >= 0
};
},
{
urls:["*://*.tumblr.com/*"]
},
["blocking"]
);
Or using the chrome.declarativeWebRequest
API (omitted chrome.runtime.onInstalled
event for brevity):
chrome.declarativeWebRequest.onRequest.addRules({
id: 'some rule id',
conditions: [
new chrome.declarativeWebRequest.RequestMatcher({
url: {
hostContains: 'cola',
hostSuffix: '.tumblr.com'
}
})
],
actions: [
new chrome.declarativeWebRequest.CancelRequest()
]
});