」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 Chrome 擴充功能中檢索 HTTP 回應正文:可能嗎?

如何在 Chrome 擴充功能中檢索 HTTP 回應正文:可能嗎?

發佈於2024-11-08
瀏覽:628

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