Home >Web Front-end >JS Tutorial >How do I capture HTTP response bodies within a Chrome extension?
How to Capture HTTP Response Bodies in Chrome Extensions
Introduction:
In Chrome extensions, obtaining information about HTTP requests is essential for many tasks, such as analyzing network traffic or modifying responses. While it's straightforward to access request bodies, retrieving response bodies poses a greater challenge.
Getting HTTP Response Bodies:
Initially, accessing response bodies directly from Chrome extensions was nearly impossible. However, the solution now lies in utilizing the Network.getResponseBody API from the Chrome DevTools protocol.
Using the Network.getResponseBody API:
To capture response bodies using the Network.getResponseBody API, follow these steps:
Code Example:
<code class="javascript">chrome.tabs.query( { currentWindow: true, active: true }, function (tabArray) { let currentTab = tabArray[0]; chrome.debugger.attach( { tabId: currentTab.id }, "1.0", onAttach.bind(null, currentTab.id) ); } ); function onAttach(tabId) { chrome.debugger.sendCommand({ tabId: tabId }, "Network.enable"); chrome.debugger.onEvent.addListener(allEventHandler); } function allEventHandler(debuggeeId, message, params) { if (currentTab.id != debuggeeId.tabId) { return; } if (message == "Network.responseReceived") { chrome.debugger.sendCommand( { tabId: debuggeeId.tabId }, "Network.getResponseBody", { requestId: params.requestId }, function (response) { // Access the response body in 'response.body' // Close the debugger (optional) chrome.debugger.detach(debuggeeId); } ); } }</code>
Note:
The debugger functionality, including this API, is only available in background scripts. You cannot use this technique in content scripts, which run within page contexts.
The above is the detailed content of How do I capture HTTP response bodies within a Chrome extension?. For more information, please follow other related articles on the PHP Chinese website!