1

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"]
);
4

1 回答 1

2

您的代码失败,因为*://*cola*.tumblr.com/*不是有效的匹配模式。通配符只能用于 URL 的路径部分,或主机名的开头。

如果要屏蔽子域包含某个关键字的 URL,则需要匹配整个域,并使用 JavaScript 检查子域是否包含亵渎词。

chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        var hostname = details.url.split('/', 3)[2];
        return {
            cancel: hostname.indexOf('cola') >= 0
        };
    },
    {
        urls:["*://*.tumblr.com/*"]
    },
    ["blocking"]
);

或使用chrome.declarativeWebRequestAPI(为简洁起见,省略chrome.runtime.onInstalled事件):

chrome.declarativeWebRequest.onRequest.addRules({
    id: 'some rule id',
    conditions: [
        new chrome.declarativeWebRequest.RequestMatcher({
            url: {
                hostContains: 'cola',
                hostSuffix: '.tumblr.com'
            }
        })
    ],
    actions: [
        new chrome.declarativeWebRequest.CancelRequest()
    ]
});
于 2013-11-13T17:47:35.757 回答