How to Retrieve HTTP Response Body in Chrome Extensions
Retrieving HTTP response body within a Chrome extension background script presents a challenge. While the extension can access the request body using chrome.webRequest.onBeforeRequest, getting the response body is typically not possible.
To overcome this limitation, a creative approach involves leveraging the chrome.debugger API. This API allows extensions to debug and interact with the browser's network activity. Here's a detailed implementation:
// 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 ...
});
}
});
This method allows you to retrieve the HTTP response body without the need for additional browser pages or third-party services. Note that you can close the debugging session using chrome.debugger.detach when you're finished.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3