"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Capture HTTP Header Responses in a Chrome Extension?

How to Capture HTTP Header Responses in a Chrome Extension?

Published on 2024-11-26
Browse:199

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);

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/*"]
}]

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3