Home >Web Front-end >JS Tutorial >How can I capture HTTP headers of requests and responses from a specific website within a Chrome extension?

How can I capture HTTP headers of requests and responses from a specific website within a Chrome extension?

Susan Sarandon
Susan SarandonOriginal
2024-11-08 16:00:03812browse

How can I capture HTTP headers of requests and responses from a specific website within a Chrome extension?

Read HTTP Responses in Chrome Extensions

Obtaining the header of a response received from a website in a Chrome extension is not straightforward. Chrome Extension APIs do not provide direct functionality like that for requests. However, an alternative solution exists.

By implementing a technique that injects a script into the DOM of a website, you can capture both HTTP requests and responses made by that website. Various methods exist for script injection, but one approach suitable for this task is ManifestV2/V3's declarative content script paired with injection.js.

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

injected.js:

This script injects into the page and intercepts requests and responses. It's inspired by a method described in How we captured AJAX requests from a website tab with a Chrome Extension.

(function(xhr) {
    var XHR = XMLHttpRequest.prototype;
    var open = XHR.open;
    var send = XHR.send;
    var setRequestHeader = XHR.setRequestHeader;

    XHR.open = function(method, url) {
        this._method = method;
        this._url = url;
        this._requestHeaders = {};
        this._startTime = (new Date()).toISOString();

        return open.apply(this, arguments);
    };

    XHR.setRequestHeader = function(header, value) {
        this._requestHeaders[header] = value;
        return setRequestHeader.apply(this, arguments);
    };

    XHR.send = function(postData) {
        this.addEventListener('load', function() {
            var endTime = (new Date()).toISOString();
            var myUrl = this._url ? this._url.toLowerCase() : this._url;
            if (myUrl) {
                if (postData) {
                    if (typeof postData === 'string') {
                        try {
                            this._requestHeaders = postData; 
                        } catch(err) {
                            console.log('Request Header JSON decode failed, transfer_encoding field could be base64');
                            console.log(err);
                        }
                    } else if (typeof postData === 'object' || typeof postData === 'array' || typeof postData === 'number' || typeof postData === 'boolean') {
                            // do something if you need
                    }
                }
                var responseHeaders = this.getAllResponseHeaders();
                if (this.responseType != 'blob' && this.responseText) {
                    try {
                        var arr = this.responseText;
                        console.log(this._url);
                        console.log(JSON.parse(this._requestHeaders));
                        console.log(responseHeaders);
                        console.log(JSON.parse(arr));                        
                    } catch(err) {
                        console.log("Error in responseType try catch");
                        console.log(err);
                    }
                }
            }
        });

        return send.apply(this, arguments);
    };
})(XMLHttpRequest);

manifest.json:

{
  "manifest_version": 3,
  "name": "Extension Name",
  "description": "Some Desc.",
  "version": "1.1",
  "content_scripts": [
    {
      "matches": ["*://website.com/*"],
      "run_at": "document_start",
      "js": ["contentscript.js", "inject.js"]
    }
  ],
  "web_accessible_resources": [
    {
      "resources": ["injected.js"],
      "matches": ["*://website.com/*"]
    }
  ]
}

With this technique, you can access HTTP headers for both requests and responses within your Chrome extension.

The above is the detailed content of How can I capture HTTP headers of requests and responses from a specific website within a Chrome extension?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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