• Skip to main content
  • Select language
  • Skip to search
MDN Web Docs
  • Technologies
    • HTML
    • CSS
    • JavaScript
    • Graphics
    • HTTP
    • APIs / DOM
    • WebExtensions
    • MathML
  • References & Guides
    • Learn web development
    • Tutorials
    • References
    • Developer Guides
    • Accessibility
    • Game development
    • ...more docs
Add-ons
  1. MDN
  2. Mozilla
  3. Add-ons
  4. Browser extensions
  5. Intercept HTTP requests

Intercept HTTP requests

In This Article
  1. Logging request URLs
  2. Redirecting requests
  3. Modifying request headers
  4. Learn more

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 module:

  • 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. The {urls: ["<all_urls>"]} pattern means we will intercept HTTP requests to all URLs.

To test it out, install the extension, open the Browser Console, and open some Web pages. In the Browser Console, you should see the URLs for any resources that the browser requests:

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://mdn.mozillademos.org"
  ],
  "background": {
    "scripts": ["background.js"]
  }
}

The only change here is to add the "webRequestBlocking" permission. We need to ask for this extra permission whenever we are actively modifying a request.

Next, replace "background.js" with this:

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"
  };
}
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 will replace the target URL with the redirectUrl specified in the function.

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://mdn.mozillademos.org/" (2) for image resources. See 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. See the webRequest.onBeforeRequest documentation for more on "blocking".

To test it out, open a page on MDN that contains a lot of images (for example https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor), reload the extension, and then reload the MDN page:

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/".

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

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) {
  for (var header of e.requestHeaders) {
    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. 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 extension, reload useragentstring.com, and check that Firefox is now identified as Opera:

Learn more

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

Document Tags and Contributors

Tags: 
  • Add-ons
  • Extensions
  • How-to
  • WebExtensions
 Contributors to this page: andrewtruongmoz, spotter, freaktechnik, MinusWall, wbamberg, chrisdavidmills
 Last updated by: andrewtruongmoz, Jul 7, 2017, 2:39:30 PM
See also
  1. Browser extensions
  2. Getting started
    1. What are extensions?
    2. Your first extension
    3. Your second extension
    4. Anatomy of an extension
    5. Example extensions
  3. How to
    1. Intercept HTTP requests
    2. Modify a web page
    3. Add a button to the toolbar
    4. Implement a settings page
  4. User interface
    1. Introduction
    2. Toolbar button
    3. Address bar button
    4. Sidebar
    5. Context menu items
    6. Options page
    7. Bundled web pages
    8. Notifications
    9. Address bar suggestions
    10. Developer tools panels
  5. Concepts
    1. Using the JavaScript APIs
    2. Content scripts
    3. Match patterns
    4. Internationalization
    5. Content Security Policy
    6. Native messaging
  6. Porting
    1. Porting a Google Chrome extension
    2. Porting a legacy Firefox extension
    3. Embedded WebExtensions
    4. Comparison with the Add-on SDK
    5. Comparison with XUL/XPCOM extensions
    6. Chrome incompatibilities
    7. Differences between desktop and Android
  7. Firefox workflow
    1. Temporary Installation in Firefox
    2. Debugging
    3. Developing for Firefox for Android
    4. Getting started with web-ext
    5. web-ext command reference
    6. Extensions and the Add-on ID
    7. Publishing your extension
  8. JavaScript APIs
    1. Browser support for JavaScript APIs
    2. alarms
    3. bookmarks
    4. browserAction
    5. browsingData
    6. commands
    7. contextMenus
    8. contextualIdentities
    9. cookies
    10. devtools.inspectedWindow
    11. devtools.network
    12. devtools.panels
    13. downloads
    14. events
    15. extension
    16. extensionTypes
    17. history
    18. i18n
    19. identity
    20. idle
    21. management
    22. notifications
    23. omnibox
    24. pageAction
    25. permissions
    26. privacy
    27. proxy
    28. runtime
    29. sessions
    30. sidebarAction
    31. storage
    32. tabs
    33. topSites
    34. types
    35. webNavigation
    36. webRequest
    37. windows
  9. Manifest keys
    1. applications
    2. author
    3. background
    4. browser_action
    5. chrome_settings_overrides
    6. chrome_url_overrides
    7. commands
    8. content_scripts
    9. content_security_policy
    10. default_locale
    11. description
    12. developer
    13. devtools_page
    14. homepage_url
    15. icons
    16. incognito
    17. manifest_version
    18. name
    19. omnibox
    20. optional_permissions
    21. options_ui
    22. page_action
    23. permissions
    24. protocol_handlers
    25. short_name
    26. sidebar_action
    27. version
    28. web_accessible_resources
  10. Themes
  11. Publishing add-ons
  12. Guides
    1. Signing and distribution overview
    2. Submit an add-on
    3. Creating an appealing listing
    4. Review policies
    5. Developer agreement
    6. Featured add-ons
    7. Contact addons.mozilla.org
  13. Community and support
  14. Channels
    1. Add-ons blog
    2. Add-on forums
    3. Stack Overflow
    4. Development newsgroup
    5. IRC Channel
  15. Legacy add-ons
  16. Legacy technologies
    1. Add-on SDK
    2. Legacy Firefox for Android
    3. Bootstrapped extensions
    4. Overlay extensions