【发布时间】:2017-10-07 20:00:13
【问题描述】:
到目前为止我所拥有的:
manifest.json
{
"name": "Testing",
"version": "0.1",
"manifest_version": 2,
"description": "Hi there.",
"background": {
"scripts": ["background.js"]
},
"icons": {
"128" : "images/test.png"
},
"browser_action": {
"default_icon": "images/test2.png",
"default_title": "test"
},
"permissions": [
"webRequest",
"webRequestBlocking",
"https://www.google.com/*",
"http://www.dictionary.com/*"
]
}
background.js
chrome.webRequest.onBeforeRequest.addListener(function(details) {
return {cancel: true};
},
{urls: ["https://www.google.com", "http://www.dictionary.com/*"]},
["blocking"]);
我希望通过加载这个解压缩的扩展程序,它会“阻止”列出的网站(使用 Google.com 和 dictionary.com 进行测试)。我不确定阻止功能实际上是如何工作的,但我认为要么网站无法加载,要么会显示某种一般错误。
但是,似乎什么都没有发生,所以我猜测要么是我对“阻塞”的理解存在缺陷,要么是我的代码没有正确编写。我的代码基于这些参考:
https://developer.chrome.com/extensions/examples/extensions/catblock/manifest.json https://developer.chrome.com/extensions/examples/extensions/catblock/background.js https://developer.chrome.com/extensions/webRequest
“以下示例以更有效的方式实现了相同的目标,因为不针对 www.evil.com 的请求不需要传递给扩展:
chrome.webRequest.onBeforeRequest.addListener(
function(details) { return {cancel: true}; },
{urls: ["*://www.evil.com/*"]},
["blocking"]); "
这是我第一次尝试制作 chrome 扩展程序,我对 html 或 javascript 并不十分熟悉,所以如果我的实现偏离了标准,请见谅。
【问题讨论】:
-
总是使用 devtools 调试器。在这种情况下for the background page。您将看到一个错误:
https://www.google.com不是有效模式。只需添加/* -
@wOxxOm 好的,我将两个条目都更改为 ://.google.com/ 我检查了调试器工具,没有看到任何错误,但扩展名似乎仍然没有做任何事情。
-
显然你没有重新加载扩展。 chrome://extensions 页面上有一个
Reload操作链接。 -
@wOxxOm 我设法让它工作了:
function blockRequest(details) { return {cancel: true}; } function updateFilters(urls) { if(chrome.webRequest.onBeforeRequest.hasListener(blockRequest)) chrome.webRequest.onBeforeRequest.removeListener(blockRequest); chrome.webRequest.onBeforeRequest.addListener(blockRequest, {urls: ["*://*.google.com/*"]}, ['blocking']); } updateFilters();不知道为什么以前的实现不起作用。 -
添加
/*后,原始发布的代码才有效。无需删除侦听器。它什么也不做,因为 API 无论如何都不会注册侦听器的第二个副本。如果它对您不起作用,则说明您做错了其他事情。