How to Intercept HTTP requests in web extension ?
Last Updated :
07 Apr, 2025
In this article, we will understand to intercept the HTTP requests made by the browser using web extension API.
What is Intercepting HTTP Request?
Intercepting HTTP Requests means manipulating the HTTP requests made by the browser through the user or through asynchronous event handlers. With the help of web extension API, you can intercept any kind of web requests which are done in your browser. For example, you can change the request structure or log the request details on the console.
To intercept HTTP requests, use the webRequest API. This API enables you to add listeners for various stages of making an HTTP request.
With these listeners you can do the following:
- Get access to request headers and bodies and response headers.
- Cancel and redirect requests.
- Modify request and response headers.
Steps to follow to use this API:
- To use this API you need to provide special permission in the manifest.json file.
- This API can only be accessed using the background script so specify the background field in the manifest.json file.
Example manifest.json:
{
"name": "webRequest",
"version": "1.0.0",
"description": "webRequests",
"manifest_version": 2,
"permissions": [
"webRequest",
"<all_urls>"
],
"background": {
"scripts": ["background.js"]
}
}
Permissions for webRequest API:
- webRequest: To get access to the request object
- webRequestBlocking: To block the ongoing request
About the event and listener:
webRequest.onBeforeRequest is the listener used to get access to the HTTP requests.
This listener is triggered when a request is about to be made, and before headers are available.
onBeforeRequest has three functions :
1. addListener: Through this, we can add a listener to this event.
Syntax:
browser.webRequest.onBeforeRequest.addListener(
listener,
filter,
extraInfoSpec
)
Where:
- listener: Callback that returns the details object
- filter: A filter that restricts the events that will be sent to this listener.
- extraInfoSpec: array of string. Extra options for the event. You can pass any of the following values:
- "blocking": make the request synchronous, so you can cancel or redirect the request
- "requestBody": include requestBody in the details object passed to the listener
2. removeListener: Through this method,we can stop listening to this event.
Syntax:
browser.webRequest.onBeforeRequest.removeListener(listener)
3. hasListener: Using this method we can check whether the listener is registered for this event. Returns true if it is listening, false otherwise.
Syntax:
browser.webRequest.onBeforeRequest.hasListener(listener)
Let's understand with the help of examples.
Example 1: In this example, we will log the request messages using the webRequest API.
steps:
- load the extension
- open the background script and inspect the page
In the below file, you are providing access to the web extension API and helping your browser to load the extension.
manifest.json
{
"description": "webRequests",
"manifest_version": 2,
"name": "webRequest",
"version": "1.0",
"permissions": [
"webRequest",
"<all_urls>"
],
"background": {
"scripts": ["app.js"]
}
}
In the below app.js file you are logging the request URL on before the request.
JavaScript
// app.js
function logURL(requestDetails) {
console.log(`Loading: ${requestDetails.url}`);
}
browser.webRequest.onBeforeRequest.addListener(
logURL,
{ urls: ["<all_urls>"] }
);
Output:
Example 2: In this example, we will replace all the images from https://media.geeksforgeeks.org/ with https://media.geeksforgeeks.org/wp-content/uploads/20220830173608/Screenshot20220830173552.png
In the below file, you are providing access to the web extension API and helping your browser to load the extension.
manifest.json
{
"description": "webRequests",
"manifest_version": 2,
"name": "webRequest",
"version": "1.0",
"permissions": [
"webRequest",
"webRequestBlocking",
"https://www.geeksforgeeks.org/","https://media.geeksforgeeks.org/"
],
"background": {
"scripts": ["app.js"]
}
}
In the below file, you are changing all the images to https://media.geeksforgeeks.org/wp-content/uploads/20220830173608/Screenshot20220830173552.png
app.js
JavaScript
let pattern = "https://media.geeksforgeeks.org/*";
const targetUrl =
"https://media.geeksforgeeks.org/wp-content/uploads/20220830173608/Screenshot20220830173552.png";
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", "imageset", "media"] },
["blocking"]
);
Output:
Similar Reads
How to call web services in HTML5 ?
In this article, we will see how to call the Web Services in HTML5, along with knowing different methods for calling the web services & understand them through the examples. Web services in HTML5 are a set of open protocols and standards that allow data to be exchanged between different applicat
3 min read
How is HTTP used in API Development ?
HTTP (Hypertext Transfer Protocol) plays a vital role in API (Application Programming Interface) development as it facilitates communication between clients and servers. Here's an in-depth look at how HTTP is used in API development: Table of Content Client-Server CommunicationHTTP MethodsHTTP Heade
3 min read
What is Server-Sent Events in HTML5 ?
Server-Sent events (SSE) provide a seamless way to automatically update web pages without requiring user interaction. These events allow servers to push real-time data to clients over HTTP connections. The updates for any website come via HTTP connections. This way of communication of updating the
3 min read
Explain Request Verbs
HTTP methods provide a way to specify the desired action to be performed on the given resource. The result depends upon the implementation of the server and it can be pre-existing data or data that is dynamically generated. The HTTP methods that are most commonly used are GET, POST, PUT, PATCH, and
4 min read
How to define the HTTP method for sending data to the action URL in HTML5?
In this article, we will learn how to define an HTTP method to send data to the action URL. The method attribute is used to indicate how form data can be sent to the given server in the action URL. The form-data may be sent using the GET or POST method depending on the requirement. The differences b
2 min read
How to Manipulate DOM using Service Worker ?
Using a service worker, indirectly manipulates the DOM through communication with the client page it controls. DOM (Document Object Model)In JavaScript, the DOM (document object model) is a programming interface that represents the structure of HTML or XML files as a hierarchical tree shape. It prov
5 min read
HTTP status codes | Client Error Responses
The browser and the site server have a conversation in the form of HTTP status codes. The server gives responses to the browserâs request in the form of a three-digit code known as HTTP status codes. The categorization of HTTP status codes is done in five sections which are listed below. Information
4 min read
How to give the value associated with the http-equiv or name attribute in HTML5 ?
The http-equiv and name attribute are specified in the meta tag in an HTML program. The meta tag is included at the head of the HTML document. It is used to define the metadata (data that describes data) about the HTML document. There are a lot of different elements under meta, but we will be discus
2 min read
HTTP REST API Calls in ElectronJS
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.W
13 min read
HTTP status codes | Informational Responses
The HTTP status codes are used to indicate that any specific HTTP request has successfully completed or not. The HTTP status codes are categorized into five sections those are listed below: Informational responses (100â199) Successful responses (200â299) Redirects (300â399) Client errors (400â499) S
2 min read