Chrome扩展程序可有效阻止域名

use*_*331 10 google-chrome google-chrome-extension

我正在制作一个非常简单的Chrome扩展程序来阻止对某些域的请求(厌倦了许多网站上的慢页面加载,等待Facebook垃圾邮件).我的问题是如何有效加载用户指定的域列表.该浏览器的文件指出,这是更有效地传递包含"网址"传递给addListener调用,而不是传递的所有请求,并在我的功能检查地图.我该怎么做,但使用用户提供的域/表达式列表?

到目前为止,这是我的清单和js文件:

的manifest.json

{
  "name": "I Don't Want YOur Social Networking Junk",
  "version": "1.0",
  "description": "This extension let's you block (Chrome will not download) content from domains.  Too many sites slow themselves down by bringing in a bunch of junk from sites like facebook.  This will let you block those things.",
  "permissions": ["webRequest", "webRequestBlocking", "http://*/*", "https://*/*"],
  "background": {
    "scripts": ["background.js"]
  },

  "manifest_version": 2
}
Run Code Online (Sandbox Code Playgroud)

background.js

chrome.webRequest.onBeforeRequest.addListener(
function(details) {
    return {cancel: true}; 
}, { urls: ["*://*.facebook.com/*", "*://*.facebook.net/*"] }, ["blocking"]);
Run Code Online (Sandbox Code Playgroud)

如您所见,我现在在网址列表中有几个硬编码表达式.这就是我想要从用户可以填充的内容中加载的内容.建议?

方 觉*_*方 觉 11

使用这样的东西:

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: urls}, ['blocking']);
}
Run Code Online (Sandbox Code Playgroud)

您可以提供一个选项页面,让用户指定要阻止的域(最好使用chrome.storage API 保存它们).在后台页面中,通过在初始化或更改设置时重新注册侦听器来更新过滤器.

顺便说一句,您应该在声明稳定时使用声明式Web请求API,因为它更有效并且不需要持久的后台页面.