Block URL with a specific word somewhere in the subdomain

自古美人都是妖i 提交于 2019-12-01 11:10:20

问题


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

回答1:


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()
    ]
});


来源:https://stackoverflow.com/questions/19956976/block-url-with-a-specific-word-somewhere-in-the-subdomain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!