javascript 用于读取HTTP响应的Chrome扩展

qyzbxkaa  于 2023-03-21  发布在  Java
关注(0)|答案(2)|浏览(111)

我有一个Chrome扩展程序,它会在发送请求之前修改请求的头部。我现在希望能够在同一个扩展程序中检查响应的头部。我搜索了整个Chrome扩展程序API,但没有找到任何感兴趣的内容。
这是我用来修改请求头的代码,也许它对你知道我是怎么做的很有用。

chrome.webRequest.onBeforeSendHeaders.addListener(
      function(details) {/*do something*/},
      {urls: ["<all_urls>"]},
      ["blocking", "requestHeaders"]);

有谁知道怎么做,或者能给我指出一个有趣的来源吗?谢谢

8zzbczxx

8zzbczxx1#

我通过向DOM注入脚本来捕获网站发出的所有HTTP请求和响应。根据您的需求和环境,有several methods of doing it,例如ManifestV 3/V2。下面是我使用的一个:

inject.js:
var s = document.createElement('script');
// must be listed in web_accessible_resources in manifest.json
s.src = chrome.runtime.getURL('injected.js');
s.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(s);

这将在与manifest.json中的“content_scripts”“matches”匹配的网站中注入injected.js。在“js”中提到contentscript.js和inject.js。请参阅答案末尾的manifest.json。
现在,injected.js中实际捕获请求和响应的代码受到了How we captured AJAX requests from a website tab with a Chrome Extension的启发。另请参阅该文章中的评论部分。

injected.js:
(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 {
                            // here you get the REQUEST HEADERS, in JSON format, so you can also use JSON.parse
                            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
                    }
                }

                // here you get the RESPONSE HEADERS
                var responseHeaders = this.getAllResponseHeaders();

                if ( this.responseType != 'blob' && this.responseText) {
                    // responseText is string or null
                    try {

                        // here you get RESPONSE TEXT (BODY), in JSON format, so you can use JSON.parse
                        var arr = this.responseText;

                        // printing url, request headers, response headers, response body, to console

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

对于MV 2,最后一个块仅为"web_accessible_resources": ["injected.js"]

hzbexzde

hzbexzde2#

请参见live-headers示例。
http://code.google.com/chrome/extensions/examples/api/debugger/live-headers.zip
编辑:为了方便后人,你可以在live-headers.zip的bug/补丁存档网站https://chromiumcodereview.appspot.com/9289057上找到一个版本
随着最新版本(2021)不再包括zip,但这是目录https://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/docs/examples/api/debugger/live-headers/?pathrev=226223

相关问题