Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

拦截HTTP请求

这篇翻译不完整。请帮忙从英语翻译这篇文章

使用 webRequest API可以拦截HTTP请求。该API允许开发者植入一个侦听器用以侦听各个阶段的HTTP请求。在侦听器中,你能:

  • GET请求及其返回的header和body
  • 取消或重定向请求
  • 修改请求及其返回的header

本文将探究webRequest模型的三种用法:

  • 登陆请求的构造
  • 重定向请求
  • 修改请求的header

记录请求的 URL

新建一个名为requests的目录,在其中新建一个名为manifest.json的文件,文件包含如下 内容 :

{
  "description": "Demonstrating webRequests",
  "manifest_version": 2,
  "name": "webRequest-demo",
  "version": "1.0",

  "permissions": [
    "webRequest"
  ],

  "background": {
    "scripts": ["background.js"]
  }
}

接着新加一个名为background.js的文件,包含如下内容:

function logURL(requestDetails) {
  console.log("Loading: " + requestDetails.url);
}

chrome.webRequest.onBeforeRequest.addListener(
  logURL,
  {urls: ["<all_urls>"]}
);

这里我们在请求开始之前用onBeforeRequest调用logURL()函数。logURL()函数抓取从事件对象发出的请求中的URL,然后将其打印到浏览器的控制台窗口中。参数{urls: ["<all_urls>"]}表示拦截发往所有URL的HTTP请求。

测试方法是:安装该WebExtension打开浏览器的控制台,然后开启某个网页即可。在浏览器控制台中就能见到浏览器请求所有资源的URL:

重定向请求

现在让我们用webRequest来重定向HTTP请求。首先将manifest.json文件内容替换如下:

{

  "description": "Demonstrating webRequests",
  "manifest_version": 2,
  "name": "webRequest-demo",
  "version": "1.0",

  "permissions": [
    "webRequest", "webRequestBlocking"
  ],
 
  "background": {
    "scripts": ["background.js"]
  }

}

这里唯一的变化是权限里 新增了webRequestBlocking项。新增这个权限是为了随时都能修改请求。

下一步替换background.js文件内容如下:

var pattern = "https://mdn.mozillademos.org/*";

function redirect(requestDetails) {
  console.log("Redirecting: " + requestDetails.url);
  return {
    redirectUrl: "https://38.media.tumblr.com/tumblr_ldbj01lZiP1qe0eclo1_500.gif"
  };
}

chrome.webRequest.onBeforeRequest.addListener(
  redirect,
  {urls:[pattern], types:["image"]},
  ["blocking"]
);

此外在请求构造出来之前我们用onBeforeRequest事件侦听器来实现URL替换。侦听器将会用redirectUrl指定的内容替换原有的URL。

这次我们不拦截所有的请求:{urls:[pattern], types:["image"]}选项告诉浏览器必须同时满足如下两点的请求才会被拦截:(1)在 https://mdn.mozillademos.org/之下的URL; (2)图片资源。该功能的更多说明参见webRequest.RequestFilter

刚才我们忽略了“blocking选项。要修改请求就要用到“blocking选项,该选项让侦听器函数阻塞住发往网络请求,浏览器将会等待侦听器返回才会继续处理。阅读webRequest.onBeforeRequest以了解更多有关“blocking 的细节。.

测试时打开MDN上的一个包含诸多图片的页面(如https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor ),重新加载WebExtension,然后重新加载这个页面:

修改请求的头部

Finally we'll use webRequest to modify request headers. In this example we'll modify the "User-Agent" header so the browser identifies itself as Opera 12.16, but only when visiting pages under https://useragentstring.com/".

The "manifest.json" can stay the same as in the previous example.

Replace "background.js" with code like this:

var targetPage = "https://useragentstring.com/*";

var ua = "Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16";

function rewriteUserAgentHeader(e) {
  for (var header of e.requestHeaders) {
    if (header.name == "User-Agent") {
      header.value = ua;
    }
  }
  return {requestHeaders: e.requestHeaders};
}

chrome.webRequest.onBeforeSendHeaders.addListener(
  rewriteUserAgentHeader,
  {urls: [targetPage]},
  ["blocking", "requestHeaders"]
);

Here we use the onBeforeSendHeaders event listener to run a function just before the request headers are sent.

The listener function will be called only for requests to URLs matching the targetPage pattern. Also note that we've again passed "blocking" as an option. We've also passed "requestHeaders", which means that the listener will be passed an array containing the request headers that we expect to send. See webRequest.onBeforeSendHeaders for more information on these options.

The listener function looks for the "User-Agent" header in the array of request headers, replaces its value with the value of the ua variable, and returns the modified array. This modified array will now be sent to the server.

To test it out, open useragentstring.com and check that it identifies the browser as Firefox. Then reload the add-on, reload useragentstring.com, and check that Firefox is now identified as Opera:

了解更多

To learn about all the things you can do with the webRequest API, see its reference documentation.

文档标签和贡献者

 此页面的贡献者: onbug
 最后编辑者: onbug,