我正在制作一个非常简单的 Chrome 扩展来阻止对某些域的请求(厌倦了许多网站上缓慢的页面加载,等待 Facebook 垃圾)。我的问题是关于如何有效加载用户指定的域列表。这Chrome 文档 https://developer.chrome.com/extensions/webRequest.html指出将包含“url”的映射传递给 addListener 调用比传递所有请求并在我的函数中检查它们更有效。除了使用用户提供的域/表达式列表之外,我该如何做到这一点?
到目前为止,这是我的清单和 js 文件:
清单.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
}
背景.js
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
return {cancel: true};
}, { urls: ["*://*.facebook.com/*", "*://*.facebook.net/*"] }, ["blocking"]);
正如您所看到的,我现在在 url 列表中有几个硬编码表达式。这就是我想从用户可以填充的内容中加载的内容。建议?
使用这样的东西:
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']);
}
您可以提供一个选项页 https://developer.chrome.com/extensions/options.html让用户指定要阻止的域(最好将它们保存为铬存储 https://developer.chrome.com/extensions/storage.html应用程序编程接口)。在后台页面中,在初始化或设置更改时,通过重新注册侦听器来更新过滤器。
顺便说一下,你应该使用声明式 Web 请求 API https://developer.chrome.com/extensions/declarativeWebRequest.html当它稳定时,因为它效率更高并且不需要持久的后台页面。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)