如何在 Chrome 擴充功能中擷取 HTTP 回應內文
在 Chrome 擴充功能後台腳本中擷取 HTTP 回應內文是一項挑戰。雖然擴充功能可以使用 chrome.webRequest.onBeforeRequest 存取請求正文,但通常無法取得回應正文。
為了克服此限制,一種創造性的方法涉及利用 chrome.debugger API。此 API 允許擴充功能調試瀏覽器的網路活動並與之互動。以下是詳細實作:
// 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 關閉偵錯會話。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3