Home > Web Front-end > JS Tutorial > How to Capture HTTP Header Responses in a Chrome Extension?

How to Capture HTTP Header Responses in a Chrome Extension?

Patricia Arquette
Release: 2024-11-06 18:40:02
Original
323 people have browsed it

How to Capture HTTP Header Responses in a Chrome Extension?

Capturing HTTP Header Responses in a Chrome Extension

Background

Chrome extensions provide the functionality to modify request headers before sending them. However, accessing response headers is not directly supported by the extension APIs.

Solution: DOM Script Injection

One approach to capturing HTTP responses is to inject a script into the website's DOM to monitor network activity. This technique uses the following code:

// Background script: inject.js
var s = document.createElement('script');
s.src = chrome.runtime.getURL('injected.js');
s.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(s);

// Content script: injected.js
(function(xhr) {

    // Override XMLHttpRequest methods
    var XHR = XMLHttpRequest.prototype;

    ['open', 'setRequestHeader', 'send'].forEach(function(method) {
        var originalMethod = XHR[method];

        XHR[method] = function() {
            // Intercept events and capture request and response headers
            ...
        };
    });

})(XMLHttpRequest);
Copy after login

Manifest Configuration

To inject the script, update the extension's manifest.json as follows:

"content_scripts": [{
    "matches": ["*://website.com/*"],
    "run_at": "document_start",
    "js": ["contentscript.js", "inject.js"]
}],
"web_accessible_resources": [{
    "resources": ["injected.js"],
    "matches": ["*://website.com/*"]
}]
Copy after login

Result

This solution allows the extension to capture and log both request and response headers, enabling the extension to retrieve the desired headers from the response.

The above is the detailed content of How to Capture HTTP Header Responses in a Chrome Extension?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template