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

半世苍凉 提交于 2019-12-18 10:11:49

问题


I'd like to read (not modify) the response body for all requests that match some pattern in a Chrome extension. I'm currently using chrome.devtools.network.onRequestFinished, which gives you a Request object with a getContent() method. This works just fine, but of course requires the devtools to be open for the extension to work. Ideally the extension would be a popup, but chrome.webRequest.onCompleted doesn't seem to give access to the response body. There is a feature request to allow the webRequest API to edit response bodies - but can webRequest even read them? If not, is there any other way to read response bodies outside of devtools extensions?


回答1:


The feature request you linked to implies that there is no support for reading either:

Unfortunately, this request is not trivial. (...) Regarding reading the Response Body: This is challenging from a performance perspective. (...) So overall, this is just not easy to achieve...

So, no, there doesn't seem to be a way for an extension to access network response bodies, except for devtools.




回答2:


Here is what I did

  1. I used the chrome.webRequest & requestBody to get the post requests body
  2. I used a decoder the parse the body into a string

Here is an example

chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        if(details.method == "POST")
        // Use this to decode the body of your post
            var postedString = decodeURIComponent(String.fromCharCode.apply(null,
                                      new Uint8Array(details.requestBody.raw[0].bytes)));
           console.log(postedString)

    },
    {urls: ["<all_urls>"]},
    ["blocking", "requestBody"]
);



回答3:


If you have the this pattern of requests you can run something like that in your background.html file:

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://example.com/" + yourStringForPattern, true);
    xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      var body = xhr.responseText;
      // call some function to do something with the html body

    }
   }
   xhr.send();


来源:https://stackoverflow.com/questions/10393638/chrome-extensions-other-ways-to-read-response-bodies-than-chrome-devtools-netw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!