Chrome扩展程序 - 阅读响应正文的其他方法,而不是chrome.devtools.network?

时间:2012-05-01 04:43:48

标签: google-chrome-extension google-chrome-devtools

我想阅读(不修改)与Chrome扩展程序中某些模式匹配的所有请求的响应正文。我目前正在使用chrome.devtools.network.onRequestFinished,它为您提供了一个Request对象,其中包含getContent()方法。这工作正常,但当然需要开放devtools才能使扩展工作。理想情况下,扩展名是弹出窗​​口,但chrome.webRequest.onCompleted似乎无法访问响应正文。有一个feature request允许webRequest API 编辑响应主体 - 但webRequest是否可以读取它们?如果没有,是否还有其他方法可以读取devtools扩展之外的响应主体?

3 个答案:

答案 0 :(得分:6)

The feature request you linked表示不支持阅读:

  

不幸的是,这个请求并非无足轻重。 (...)关于阅读响应机构:从绩效角度来看,这是一项挑战。 (...)总的来说,这并不容易实现......

所以,不,除了devtools之外,似乎没有办法扩展访问网络响应机构。

答案 1 :(得分:0)

这就是我所做的

  1. 我使用chrome.webRequestrequestBody来获取帖子请求正文
  2. 我使用decoder将正文解析为字符串

这里是一个示例

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

答案 2 :(得分:-5)

如果您有这种请求模式,则可以在 background.html 文件中运行类似的内容:

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