Chrome扩展程序 - 如何获取HTTP响应正文?

oti*_*i10 28 javascript google-chrome-extension

这似乎是困难的问题(或不可能?).我想通过观看Chrome扩展程序后台脚本来获取并阅读由浏览器中的HTTP请求引起的HTTP响应.我们可以通过这种方式获得HTTP Request Body

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

我还检查了这些stackoverflows

有没有聪明的方法来获取Chrome扩展中的HTTP响应体?

小智 20

我找不到比这更好的方式了.

Chrome扩展程序可读取HTTP响应

anwser告诉如何获取 响应标头并显示在另一个页面中.但是响应obj中没有正文信息(请参阅event-responseReceived).如果你想获得 没有其他页面的响应主体,试试这个.

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

}
Run Code Online (Sandbox Code Playgroud)

我认为它对我来说足够有用,你可以chrome.debugger.detach(debuggeeId)用来关闭丑陋的小费.

抱歉,mabye没有帮助...... ^ ^

  • 我收到错误无法“附加”到 chrome://url。无论如何围绕这个并且只附加到特定的网址? (4认同)
  • 这是从后台脚本还是从内容脚本运行的? (4认同)
  • 我从上面的代码制作了一个内容脚本,并在响应正文部分添加了一个 console.log 和 alert,但没有任何反应。代码应该放在哪里? (3认同)
  • 使用`--silent调试器扩展,api`命令行开关午餐浏览器摆脱黄条的,它必须是浏览器的第一个实例 (2认同)
  • @evanjmg 如果将“tabs”放入`manifest.json` 的权限数组中,则可以查询该 url。在`chrome.tabs.query` 中,使用`function (tabArray) { currentTab = tabArray[0]; if(!currentTab.url.startsWith("chrome:")){ chrome.debugger.attach({ //debug at current tab tabId: currentTab.id }, version, onAttach.bind(null, currentTab.id)); } }` (2认同)
  • 您好,如果有人需要更多命令来获取网络信息,请点击此链接 https://chromedevtools.github.io/devtools-protocol/tot/Network (2认同)

小智 8

要获取 XHR响应正文,您可以按照此答案中的说明进行操作。

要获取 FETCH响应正文,您可以查看本文中的解决方案 3以及此答案。两者都无需使用 chrome.debugger 即可获取响应正文

简而言之,您需要使用与 XHR 请求相同的方法将以下函数从内容脚本注入到页面中。

const constantMock = window.fetch;
 window.fetch = function() {
    return new Promise((resolve, reject) => {
        constantMock.apply(this, arguments)
            .then((response) => {
                if (response) {
                    response.clone().json() //the response body is a readablestream, which can only be read once. That's why we make a clone here and work with the clone
                    .then( (json) => {
                        console.log(json);
                        //Do whatever you want with the json
                        resolve(response);
                    })
                    .catch((error) => {
                        console.log(error);
                        reject(response);
                    })
                }
                else {
                    console.log(arguments);
                    console.log('Undefined Response!');
                    reject(response);
                }
            })
            .catch((error) => {
                console.log(error);
                reject(response);
            })
    })
}
Run Code Online (Sandbox Code Playgroud)

如果response.clone().json()不起作用,你可以尝试response.clone().text()


Tar*_*gar 6

这绝对不是 Chrome 扩展生态系统开箱即用的。但是,我可以找到几种方法来解决这个问题,但这两种方法都有自己的缺点。

一种方式是:

  1. 使用内容脚本注入我们自己的自定义脚本。
  2. 使用自定义脚本扩展 XHR 的本机方法以读取响应。
  3. 将响应添加到隐藏(非display: none)元素内的网页 DOM 。
  4. 使用内容脚本读取隐藏的响应。

第二种方法是创建一个DevTools扩展其是,提供了一个API来读取每个请求的唯一扩展。

我已在此处的博客文章中详细记录了这两种方法

如果您遇到任何问题,请告诉我!:)


Joh*_*nP2 6

现在在 Chrome 开发者工具扩展中有一种方法,示例代码可以在这里看到:博客文章

简而言之,这是对他的示例代码的改编:

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.
      }
}
});
});
Run Code Online (Sandbox Code Playgroud)

  • 从文章本身来看:此方法的缺点是我们必须始终保持 Chrome DevTools 打开,因为 DevTools 扩展仅在 DevTools 打开时激活。 (5认同)