3

I saw many pages talking about how to intercept the HTTP Response from a site. I'm trying this: Chrome Extension - How to get HTTP Response Body? There are no execuble programs... this is my code:

manifest.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>

injected.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 I set a timeout so I can enable the debugger:

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

Why the code is not injected into https://www.google.com/? Inspecting the DOM I don't see the code... the code runs and xhr is started but the methods open, setRequestHeader and send are never called.

Glenn Slayden
  • 17,543
  • 3
  • 114
  • 108
Nammen8
  • 619
  • 1
  • 11
  • 31
  • Isn't [this](https://stackoverflow.com/questions/8939467/chrome-extension-to-read-http-response) the question you got the code from? Maybe you should post a comment there asking what should be in `inject.js`. – Barmar Oct 05 '18 at 15:56
  • @Barmar posted. Thanks, but I don't think is this the problem. – Nammen8 Oct 05 '18 at 15:58

1 Answers1

1

The code is from my answer here. Content Script, in that case, is used to communicate with injected.js.

Sample code is as follows:

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

    });

});

Please read more on Content Scripts. Hope you find this useful.

user5155835
  • 4,392
  • 4
  • 53
  • 97
  • thank you for the answer! It is of great help already. I am not sure you get notified - I put a bounty on the question as i have troubles turning both of your answers in a reproducible example. I dont wanna steal any of your precious time, but i am just to new to Chrome extensions to solve it myself. Thats why i decided to bring an "effort" in Terms of a bounty. – Tlatwork Aug 10 '19 at 16:42
  • sry to bother again, but is there any Chance? – Tlatwork Aug 11 '19 at 17:39
  • I have not been working on chrome extensions for a year now. What help do you need? – user5155835 Aug 12 '19 at 05:18
  • thanks for the answer. Is there any Chance you still have a reproducible form of the app that captures Network request including the Body and are processed in the Content script. Maybe an old extensions where you used the Code? Thanks so much! – Tlatwork Aug 12 '19 at 14:13
  • @ThanksGuys I can upload the entire code of the extension I was working on to Github and give you the link. Let me know – user5155835 Aug 13 '19 at 04:15
  • that would be awesome! Thank you! – Tlatwork Aug 13 '19 at 09:45
  • @ThanksGuys Here is the code: https://github.com/AniketBhadane/kumpan-phish-extension – user5155835 Aug 13 '19 at 12:51
  • @ThanksGuys did that help? – user5155835 Aug 15 '19 at 03:48
  • i am very thankful for your help. To be honest i didnt find any Network request capturing in there. Maybe i overlooked it. I found another snippet to capture them in the Background script and Transfer to contentscript. Thanks anyway, i upvoted! – Tlatwork Aug 19 '19 at 12:21