Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension - How to get HTTP Response Body?

It seems to be difficult problem (or impossible??). I want to get and read HTTP Response, caused by HTTP Request in browser, under watching Chrome Extension background script. We can get HTTP Request Body in this way

chrome.webRequest.onBeforeRequest.addListener(function(data){
    // data contains request_body
},{'urls':[]},['requestBody']);

I also checked these stackoverflows

  • Chrome extensions - Other ways to read response bodies than chrome.devtools.network?
  • Chrome extension to read HTTP response

Is there any clever way to get HTTP Response Body in Chrome Extension?

like image 368
otiai10 Avatar asked Aug 30 '13 13:08

otiai10


2 Answers

I can't find better way then this anwser.

Chrome extension to read HTTP response

The answer told how to get response headers and display in another page.But there is no body info in the response obj(see event-responseReceived). If you want to get response body without another page, try this.

var currentTab;
var version = "1.0";

chrome.tabs.query( //get current Tab
    {
        currentWindow: true,
        active: true
    },
    function(tabArray) {
        currentTab = tabArray[0];
        chrome.debugger.attach({ //debug at current tab
            tabId: currentTab.id
        }, version, onAttach.bind(null, currentTab.id));
    }
)


function onAttach(tabId) {

    chrome.debugger.sendCommand({ //first enable the Network
        tabId: tabId
    }, "Network.enable");

    chrome.debugger.onEvent.addListener(allEventHandler);

}


function allEventHandler(debuggeeId, message, params) {

    if (currentTab.id != debuggeeId.tabId) {
        return;
    }

    if (message == "Network.responseReceived") { //response return 
        chrome.debugger.sendCommand({
            tabId: debuggeeId.tabId
        }, "Network.getResponseBody", {
            "requestId": params.requestId
        }, function(response) {
            // you get the response body here!
            // you can close the debugger tips by:
            chrome.debugger.detach(debuggeeId);
        });
    }

}

I think it's useful enough for me and you can use chrome.debugger.detach(debuggeeId)to close the ugly tip.

sorry, mabye not helpful... ^ ^

like image 177
liyangready Avatar answered Nov 08 '22 20:11

liyangready


There is now a way in a Chrome Developer Tools extension, and sample code can be seen here: blog post.

In short, here is an adaptation of his sample code:

chrome.devtools.network.onRequestFinished.addListener(request => {
  request.getContent((body) => {
    if (request.request && request.request.url) {
      if (request.request.url.includes('facebook.com')) {

         //continue with custom code
         var bodyObj = JSON.parse(body);//etc.
      }
}
});
});
like image 10
JohnP2 Avatar answered Nov 08 '22 20:11

JohnP2