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.
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!