我正在尝试使用webrequest api,但我无法使用它阻止网站。
的manifest.json
{
"manifest_version": 2,
"name": "blocktwitter",
"description": "block twitter",
"version": "1.0",
"permissions": [
"https://ajax.googleapis.com/",
"activeTab",
"storage",
"webRequest",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"],
"persistent": true
}
}
background.js:
chrome.webRequest.onBeforeRequest.addListener(
function(details) { return {cancel: true}; },
{urls: ["https://twitter.com"]},
["blocking"]);
我复制了这个副本+粘贴了来自twitter的网址,并从文档中复制了代码,但它仍然无效。我不确定我做错了什么。帮助将不胜感激。
答案 0 :(得分:0)
你有两个问题。
第一个问题是您传递给chrome.webRequest.onBeforeRequest.addListener()
的网址不是有效的match pattern。匹配模式需要路径组件。如果您查看过console for your background page/script,您会看到以下错误:
_generated_background_page.html:1 Unchecked runtime.lastError while running webRequestInternal.addEventListener: 'https://twitter.com' is not a valid URL pattern.
你的 background.js 应该是这样的:
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
console.log('In webRequest');
return {cancel: true};
}, {
urls: ["https://*.twitter.com/*"]
}, ["blocking"]
);
您需要拥有要阻止的主机的权限。您必须在permissions
中的manifest.json数组中声明主机。类似的东西:
{
"manifest_version": 2,
"name": "blocktwitter",
"description": "block twitter",
"version": "1.0",
"permissions": [
"https://ajax.googleapis.com/*",
"https://*.twitter.com/*",
"activeTab",
"storage",
"webRequest",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"],
"persistent": true
}
}