javascript - Chrome 扩展 : intercept HTTP Response

标签 javascript google-chrome google-chrome-extension http-headers http-get

我看到很多页面都在谈论如何拦截来自站点的 HTTP 响应。我正在尝试这个:Chrome Extension - How to get HTTP Response Body? 没有可执行程序...这是我的代码:

list .json:

{
  "manifest_version": 2,

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

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "index.html"
  },
  "permissions": [
    "activeTab",
    "storage",
    "tabs",
    "https://*.google.com/"
  ],
  "content_scripts": [
    {
      "matches": ["https://*.google.com/"],
      "run_at": "document_start",
      "js": ["contentscript.js", "inject.js"]
    }
  ],
  "web_accessible_resources": ["injected.js"]
}

index.html:

<html>

    <head>
        <script src="contentscript.js"></script>
    </head>

    <body>
            <p>HTTP INTERCEPTOR</p>
    </body>

</html>

注入(inject).js:

(function(xhr) {
    console.log('injeced file');

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

inject.js 我设置了一个超时,这样我就可以启用调试器了:

/**
 * code in inject.js
 * added "web_accessible_resources": ["injected.js"] to manifest.json
 */

setTimeout(function() {
    var s = document.createElement('script');
    s.src = chrome.extension.getURL('injected.js');
    s.onload = function() {
        this.remove();
        console.log('remove');
    };
    (document.head || document.documentElement).appendChild(s);
}, 10000);

为什么代码没有注入(inject)https://www.google.com/?检查 DOM 我没有看到代码...代码运行并且 xhr 已启动但是方法 opensetRequestHeadersend 永远不会被调用。

最佳答案

代码来 self 的回答here . 在这种情况下,内容脚本用于与 injected.js 通信。

示例代码如下:

/**
 * Content script currently only used to communicate extension state on off message to injected.js
 * Sends back response to extension (popup.js) after sending message to injected.js
 */
$(function(){

    // localStorage is different from chrome.storage
    // localStorage for injected script, and chrome.storage for extension script (popup.js) and contentscript.js

    chrome.storage.sync.get("state", function (data) {

        if (typeof data.state === 'undefined') {
            chrome.storage.sync.set({"state": "on"}, function() {});    // async
        }

        console.log("Content Script State: " + data.state);
    });

    // message from extension script to this content script.
    // will be used to receive enable disable messages
    // sends response in 'status' variable
    chrome.runtime.onMessage.addListener(
        function(request, sender, sendResponse) {
        console.log(sender.tab ?
                    "content script receiving message from a content script:" + sender.tab.url :
                    "content script receiving message from the extension");

        if (request.toggle === true) {
            chrome.storage.sync.set({"state": "on"}, function() { console.log("Content Script State Updated: on"); });  // async
            var data = {
                app_state: "on"
            };
            document.dispatchEvent(new CustomEvent("app_state_message", {detail: data}));
            // cannot return state in function since above .set is async and popup.js does not receive the response
            sendResponse({state: "on"});
        } else if (request.toggle === false) {
            chrome.storage.sync.set({"state": "off"}, function() { console.log("Content Script State Updated: off"); });    // async
            var data = {
                app_state: "off"
            };
            document.dispatchEvent(new CustomEvent("app_state_message", {detail: data}));
            sendResponse({state: "off"});
        } else {
            sendResponse({state: "error"});
        }

    });

});

请在 Content Scripts 上阅读更多内容.希望你觉得这很有用。

关于javascript - Chrome 扩展 : intercept HTTP Response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52669328/

相关文章:

javascript - 带 if-else 的函数无法正常工作

python - 如何在没有 Selenium 的情况下使用带有 python 的浏览器

javascript - 如何在浏览器中获取 Google Cloud Translation API 的身份验证 token (chrome 扩展)

google-chrome - 带有 '403: Daily Limit Exceeded' 的日历 API 响应 - Google Chrome 扩展

javascript - MDN 的 reduce() pollyfill 的 while 循环背后的逻辑

javascript - Dom加载事件跨浏览器原生javascript代码

javascript - 如何在鼠标悬停时显示所有 div 的内部图像标题?

android - 有没有办法覆盖 Chrome 的 “Request Desktop Site” 选项?

html - 绝对定位跨越输入时的奇怪行为

javascript - onclick 或内联脚本在扩展中不起作用