Intercept HTTP requests

To intercept HTTP requests, use the webRequest API。 This API enables you to add listeners for various stages of making an HTTP request. In the listeners, you can:

  • get access to request headers and bodies, and response headers
  • cancel and redirect requests
  • modify request and response headers

In this article we'll look at three different uses for the webRequest 模块:

  • Logging request URLs as they are made.
  • Redirecting requests.
  • Modifying request headers.

Logging request URLs

Create a new directory called "requests". In that directory, create a file called "manifest.json" which has the following contents:

{
  "description": "Demonstrating webRequests",
  "manifest_version": 2,
  "name": "webRequest-demo",
  "version": "1.0",
  "permissions": [
    "webRequest",
    "<all_urls>"
  ],
  "background": {
    "scripts": ["background.js"]
  }
}

					

Next, create a file called "background.js" with the following contents:

function logURL(requestDetails) {
  console.log("Loading: " + requestDetails.url);
}
browser.webRequest.onBeforeRequest.addListener(
  logURL,
  {urls: ["<all_urls>"]}
);

					

Here we use onBeforeRequest to call the logURL() function just before starting the request. The logURL() function grabs the URL of the request from the event object and logs it to the browser console. {urls: ["<all_urls>"]} pattern means we will intercept HTTP requests to all URLs.

To test it out:

In the Browser Console, you should see the URLs for any resources that the browser requests. For example, this screenshot shows the URLs from loading a Wikipedia page:

Browser console menu : URLs from extension

Redirecting requests

Now let's use webRequest to redirect HTTP requests. First, replace manifest.json with this:

{
  "description": "Demonstrating webRequests",
  "manifest_version": 2,
  "name": "webRequest-demo",
  "version": "1.0",
  "permissions": [
    "webRequest",
    "webRequestBlocking",
    "https://developer.mozilla.org/"
  ],
  "background": {
    "scripts": ["background.js"]
  }
}

					

The changes here are to:

  • add the webRequestBlocking permission . This extra permission is needed when an extension wants to modify a request.
  • replace the <all_urls> permission with individual host permissions , as this is good practice to minimize the number of requested permissions.

Next, replace background.js with this:

var pattern = "https://developer.mozilla.org/*";
var targetUrl = "https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_second_WebExtension/frog.jpg";
function redirect(requestDetails) {
  console.log("Redirecting: " + requestDetails.url);
  if (requestDetails.url === targetUrl) {
    return;
  }
  return {
    redirectUrl: targetUrl
  };
}
browser.webRequest.onBeforeRequest.addListener(
  redirect,
  {urls:[pattern], types:["image"]},
  ["blocking"]
);

					

Again, we use the  onBeforeRequest event listener to run a function just before each request is made. This function replaces the redirectUrl with the target URL specified in the function. In this case, the frog image from the your second extension tutorial .

This time we are not intercepting every request: the {urls:[pattern], types:["image"]} option specifies that we should only intercept requests (1) to URLs residing under "https://developer.mozilla.org/" (2) for image resources. 见 webRequest.RequestFilter for more on this.

Also note that we're passing an option called "blocking" : we need to pass this whenever we want to modify the request. It makes the listener function block the network request, so the browser waits for the listener to return before continuing. 见 webRequest.onBeforeRequest documentation for more on "blocking" .

To test it out, open a page on MDN that contains a lot of images (for example the page listing extension user interface components ), reload the extension , and then reload the MDN page. You will see something like this:

Images on a page replaced with a frog image

Modifying request headers

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 http://useragentstring.com/".

Update your manifest.json to include http://useragentstring.com/

{
  "description": "Demonstrating webRequests",
  "manifest_version": 2,
  "name": "webRequest-demo",
  "version": "1.0",
  "permissions": [
    "webRequest",
    "webRequestBlocking",
    "http://useragentstring.com/"
  ],
  "background": {
    "scripts": ["background.js"]
  }
}

					

Replace "background.js" with code like this:

var targetPage = "http://useragentstring.com/*";
var ua = "Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16";
function rewriteUserAgentHeader(e) {
  e.requestHeaders.forEach(function(header){
    if (header.name.toLowerCase() == "user-agent") {
      header.value = ua;
    }
  });
  return {requestHeaders: e.requestHeaders};
}
browser.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. 见 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 extension, reload useragentstring.com , and see that Firefox is now identified as Opera.

useragentstring.com showing details of the modified user agent string

了解更多

To learn about all the things you can do with the webRequest API, see its 参考文档编制 .

Found a problem with this page?

最后修改: , 由 MDN 贡献者

  1. 浏览器扩展名
  2. 快速入门
    1. What are extensions?
    2. Your first extension
    3. Your second extension
    4. Anatomy of an extension
    5. Example extensions
    6. What next?
  3. 概念
    1. Using the JavaScript APIs
    2. Content scripts
    3. Match patterns
    4. Working with files
    5. 国际化
    6. Content Security Policy
    7. Native messaging
    8. Differences between API implementations
    9. Chrome incompatibilities
  4. 用户界面
    1. 用户界面
    2. Toolbar button
    3. Address bar button
    4. Sidebars
    5. Context menu items
    6. Options page
    7. Extension pages
    8. Notifications
    9. Address bar suggestions
    10. Developer tools panels
  5. 如何
    1. Intercept HTTP requests
    2. Modify a web page
    3. Insert external content
    4. Share objects with page scripts
    5. Add a button to the toolbar
    6. Implement a settings page
    7. Work with the Tabs API
    8. Work with the Bookmarks API
    9. Work with the Cookies API
    10. Work with contextual identities
    11. Interact with the clipboard
    12. Build a cross-browser extension
  6. Firefox differentiators
  7. JavaScript API
    1. Browser support for JavaScript APIs
    2. alarms
    3. bookmarks
    4. browserAction
    5. browserSettings
    6. browsingData
    7. captivePortal
    8. clipboard
    9. 命令
    10. contentScripts
    11. contextualIdentities
    12. Cookie
    13. devtools
    14. dns
    15. downloads
    16. events
    17. extension
    18. extensionTypes
    19. find
    20. history
    21. i18n
    22. identity
    23. idle
    24. management
    25. menus
    26. notifications
    27. omnibox
    28. pageAction
    29. permissions
    30. pkcs11
    31. privacy
    32. proxy
    33. runtime
    34. search
    35. sessions
    36. sidebarAction
    37. storage
    38. tabs
    39. theme
    40. topSites
    41. 类型
    42. userScripts
    43. webNavigation
    44. webRequest
    45. windows
  8. Manifest keys
    1. 介绍
    1. 作者
    2. background
    3. browser_action
    4. browser_specific_settings
    5. chrome_settings_overrides
    6. chrome_url_overrides
    7. 命令
    8. content_scripts
    9. content_security_policy
    10. default_locale
    11. description
    12. developer
    13. devtools_page
    14. dictionaries
    15. externally_connectable
    16. homepage_url
    17. icons
    18. incognito
    19. manifest_version
    20. name
    21. offline_enabled
    22. omnibox
    23. optional_permissions
    24. options_page
    25. options_ui
    26. page_action
    27. permissions
    28. protocol_handlers
    29. short_name
    30. sidebar_action
    31. storage
    32. theme
    33. theme_experiment
    34. user_scripts
    35. version
    36. version_name
    37. web_accessible_resources
  9. Extension Workshop
    1. Develop
    2. Publish
    3. Manage
    4. Enterprise
  10. Contact us
  11. Channels
    1. Add-ons blog
    2. Add-ons forum
    3. Add-ons chat