I'm trying to modify http response using chrome.debugger.onEvent with the Chrome DevTools Protocol Fetch API.
I tried the the following code, it is intended to modify the response for the request to "https://example.com/" otherwise bypass (set the original response, and headers, status code), but I got an error. and also I'm not very sure if I'm on the right track to do what I desired.
How can I make it work?
let tabId;
async function getTabs () {
return new Promise((resolve) => {
chrome.tabs.query({}, function (tabs) {
resolve(tabs);
});
});
}
(async () => {
let tabs = await getTabs();
let tab = tabs.filter(a => a.url.match('example.com'))?.[0]
console.log(tab);
tabId = tab.id;
chrome.debugger.attach({ tabId }, '1.3', () => {
chrome.debugger.sendCommand({ tabId }, 'Fetch.enable', {});
chrome.debugger.onEvent.addListener( async (source, method, params) => {
if (method === 'Fetch.requestPaused') {
const requestId = params.requestId;
var match = params.request.url.match('https://example.com/');
const responseBody = await new Promise((resolve) => {
chrome.debugger.sendCommand( // gets error here; TypeError: Error in invocation of debugger.sendCommand
'Fetch.getResponseBody',
{ requestId },
(response) => {
resolve(response.body);
}
);
});
const modifiedBody = 'modified body';
const modifiedResponseBody = btoa(modifiedBody);
const modifiedResponse = {
requestId,
responseCode: 200,
responseHeaders: params.responseHeaders,
body: match ? modifiedResponseBody : responseBody,
};
chrome.debugger.sendCommand({ tabId }, 'Fetch.fulfillRequest', modifiedResponse);
}
});
});
})();