Home > Article > Web Front-end > How to Capture HTTP Response Headers in Chrome Extensions?
How to Read HTTP Response Headers in Chrome Extensions
Original Post:
This question seeks to extend a Chrome extension that manipulates request headers to enable the inspection of response headers. The user was unable to locate relevant APIs in the Chrome Extension APIs.
Solution:
Capturing HTTP responses requires injecting a script into the DOM. The following code demonstrates this approach:
// 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);
This script injects injected.js, which contains the code to capture requests and responses:
// injected.js (function(xhr) { // Override XMLHttpRequest methods var XHR = XMLHttpRequest.prototype; var open = XHR.open; var send = XHR.send; var setRequestHeader = XHR.setRequestHeader; // Intercept open() to capture request details XHR.open = function(method, url) { this._method = method; this._url = url; this._requestHeaders = {}; this._startTime = (new Date()).toISOString(); return open.apply(this, arguments); }; // Intercept setRequestHeader() to track request headers XHR.setRequestHeader = function(header, value) { this._requestHeaders[header] = value; return setRequestHeader.apply(this, arguments); }; // Intercept send() to capture response details XHR.send = function(postData) { this.addEventListener('load', function() { var endTime = (new Date()).toISOString(); // Retrieve request URL, headers, and response headers var myUrl = this._url ? this._url.toLowerCase() : this._url; if (myUrl) { // Print request headers, response headers, and response body (if available in string format) console.log(this._url); console.log(JSON.parse(this._requestHeaders)); console.log(this.getAllResponseHeaders()); if ( this.responseType != 'blob' && this.responseText) { console.log(JSON.parse(this.responseText)); } } }); return send.apply(this, arguments); }; })(XMLHttpRequest);
Finally, update your manifest.json to include the necessary scripts and resources:
// manifest.json (MV3) { "manifest_version": 3, "content_scripts": [ { "matches": ["*://website.com/*"], "run_at": "document_start", "js": ["contentscript.js", "inject.js"] } ], "web_accessible_resources": [ { "resources": ["injected.js"], "matches": ["*://website.com/*"] } ] } // manifest.json (MV2) { "web_accessible_resources": ["injected.js"] }
With this approach, you can now modify request headers and capture response headers within the same Chrome extension.
The above is the detailed content of How to Capture HTTP Response Headers in Chrome Extensions?. For more information, please follow other related articles on the PHP Chinese website!