”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何在 Chrome 扩展程序中检索 HTTP 响应正文:可能吗?

如何在 Chrome 扩展程序中检索 HTTP 响应正文:可能吗?

发布于2024-11-08
浏览:660

How to Retrieve HTTP Response Body in Chrome Extensions:  Is it Possible?

如何在 Chrome 扩展程序中检索 HTTP 响应正文

在 Chrome 扩展程序后台脚本中检索 HTTP 响应正文是一项挑战。虽然扩展程序可以使用 chrome.webRequest.onBeforeRequest 访问请求正文,但通常无法获取响应正文。

为了克服此限制,一种创造性的方法涉及利用 chrome.debugger API。此 API 允许扩展程序调试浏览器的网络活动并与之交互。下面是详细实现:

  1. 使用 chrome.tabs.query 和 chrome.debugger.attach 建立与当前选项卡的连接。
  2. 通过发送 Network.enable 命令启用网络调试到选项卡。
  3. 注册 Network.responseReceived 事件的事件监听器。
  4. 收到响应后,发送 Network.getResponseBody 命令,并从事件参数中指定 requestId。
  5. 命令将返回响应正文,以便您根据需要进行处理。
// Attach to the current tab and enable network debugging.
chrome.tabs.query({ currentWindow: true, active: true }, tabs => {
  chrome.debugger.attach({ tabId: tabs[0].id }, '1.0', debuggeeId => {
    chrome.debugger.sendCommand({ tabId: debuggeeId.tabId }, 'Network.enable');
  });
});

// Listen for response received events.
chrome.debugger.onEvent.addListener((debuggeeId, message, params) => {
  if (debuggeeId.tabId !== currentTab.id) return;
  if (message === 'Network.responseReceived') {
    // Get the response body by sending a command.
    chrome.debugger.sendCommand({ tabId: debuggeeId.tabId }, 'Network.getResponseBody', { requestId: params.requestId }, response => {
      // The response body is now available.
      // ... Process the response body ...
    });
  }
});

此方法允许您检索 HTTP 响应正文,而无需额外的浏览器页面或第三方服务。请注意,完成后您可以使用 chrome.debugger.detach 关闭调试会话。

版本声明 本文转载于:1729758196如有侵犯,请联系[email protected]删除
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3