Chrome扩展程序可读取HTTP响应

Mas*_*iar 6 google-chrome-extension

我有这个Chrome扩展程序,可以在发送请求之前修改请求标头.我现在希望能够在同一扩展中检查响应的标题.我搜索了整个Chrome扩展API,但我找不到任何有趣的东西.

这是我用来修改请求标头的代码,也许对你来说知道我是怎么做的很有用.

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

有谁知道怎么做,或者可以指向一个有趣的来源?谢谢

use*_*835 12

通过向DOM注入脚本,我实现了捕获网站所做的所有HTTP请求和响应.我使用以下脚本将inject.js注入DOM:

/**
 * code in inject.js
 * added "web_accessible_resources": ["injected.js"] to manifest.json
 */
var s = document.createElement('script');
s.src = chrome.extension.getURL('injected.js');
s.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(s);
Run Code Online (Sandbox Code Playgroud)

这会在manifest.json中匹配"content_scripts""匹配"的网站中注入inject.js.在"js"中提及contentscript.js和inject.js.另外,请确保您已在manifest.json的"权限"中提及该网站.请在答案结尾处查看manifest.json.

现在,inject.js中用于实际捕获请求和响应的代码的灵感来自于我们如何从带有Chrome扩展的网站选项卡中捕获AJAX请求.另请参阅该文章中的评论部分.

inject.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);
Run Code Online (Sandbox Code Playgroud)

作为参考,我的manifest.json是:

{
  "manifest_version": 2,

  "name": "Extension Name",
  "description": "Some Desc.",
  "version": "1.1",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab",
    "storage",
    "tabs",
    "*://website.com/*"
  ],
  "content_scripts": [
    {
      "matches": ["*://website.com/*"],
      "run_at": "document_start",
      "js": ["contentscript.js", "inject.js"]
    }
  ],
  "web_accessible_resources": ["injected.js"]
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.