Chrome扩展程序:如何拦截请求的网址?

问题描述:

如果某些条件匹配,扩展程序如何拦截任何请求的URL来阻止它? (针对Firefox的类似问题

How can an extension intercept any requested URL to block it if some condition matches? (similar question for Firefox)

需要在manifest.json中设置什么权限?

What permission needs to be set in manifest.json?

JavaScript代码:

JavaScript Code :

以下示例说明了如何阻止对www.evil.com的所有请求:

The following example illustrates how to block all requests to www.evil.com:

chrome.webRequest.onBeforeRequest.addListener(
  function(details) {
    return {cancel: details.url.indexOf("://www.evil.com/") != -1};
  },
  { urls: ["<all_urls>"] },
  ["blocking"]
);

下面的示例以更有效的方式实现了相同的目标,因为未定向到www的请求。 evil.com不需要传递给扩展名:

The following example achieves the same goal in a more efficient way because requests that are not targeted to www.evil.com do not need to be passed to the extension:

chrome.webRequest.onBeforeRequest.addListener(
  function(details) { 
    return { cancel: true }; 
  },
  {urls: ["*://www.evil.com/*"]},
  ["blocking"]
);

注册事件监听器:

要为Web请求注册事件侦听器,请对通常的 addListener()函数使用一个变体。除了指定回调函数外,还必须指定过滤器参数,还可以指定可选的额外信息参数。

To register an event listener for a web request, you use a variation on the usual addListener() function. In addition to specifying a callback function, you have to specify a filter argument and you may specify an optional extra info argument.

Web请求API的三个参数addListener( )具有以下定义:

The three arguments to the web request API's addListener() have the following definitions:

var callback = function(details) {...};
var filter = {...};
var opt_extraInfoSpec = [...];

下面是一个监听onBeforeRequest事件的示例:

Here's an example of listening for the onBeforeRequest event:

chrome.webRequest.onBeforeRequest.addListener(
  callback, filter, opt_extraInfoSpec);

manifest.json所需的权限:

"permissions": [
  "webRequest",
  "webRequestBlocking",
"tabs",
"<all_urls>"
],

扩展示例和帮助链接:

  • Extension Requestly : https://chrome.google.com/webstore/detail/requestly/mdnleldcmiljblolnjhpnblkcekpdkpa
  • Extension Https-Everywhere : https://github.com/EFForg/https-everywhere
  • Example : https://github.com/blunderboy/requestly/blob/master/src/background/background.js
  • Wiki : https://code.google.com/p/html5security/wiki/RedirectionMethods
  • Wiki : https://developer.chrome.com/extensions/webRequest