我正在尝试制作一个 Chrome 扩展程序来阻止子域中包含特定单词的 URL,但不会阻止该域中的其他 URL。例如,假设我想屏蔽所有子域中包含单词“cola”的 tumblr 博客。
应该可以屏蔽这个页面:http://coca-cola.tumblr.com/ .
我尝试使用此 url 匹配:urls:["*://*cola*.tumblr.com/*"]
,但它不起作用。而且我想不出任何其他可能有效的组合。有人能指出我正确的方向吗?
这是我的完整 background.js:
chrome.webRequest.onBeforeRequest.addListener(
function() {
return {cancel: true };
},
{
urls:["*://*cola*.tumblr.com/*"] // This is the part I'm messing up.
},
["blocking"]
);
最佳答案
您的代码失败,因为 *://*cola*.tumblr.com/*
不是有效的 match pattern .通配符只能用在 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.declarativeWebRequest
API(为简洁起见省略了 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()
]
});
关于javascript - 使用子域中某处的特定词阻止 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19956976/