0

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);
        }
      });
    });

})();
  • 1) The first parameter of sendCommand is the target, your did it correctly in the first call. 2) Do you know you can override the response by overriding methods like `text` or `blob` or `json` on Response.prototype in [page context](/a/9517879) (as well as the getter for `status` via Object.defineProperty)? – wOxxOm Jul 30 '23 at 14:16
  • 1) when I try `chrome.debugger.sendCommand( tabId }, 'Fetch.getResponseBody', { requestId }, (response) =>` for some reason `response` is `undefined` and `response.body` therefore gets an error. 2) I didn't know. I don't quite understand what that mean. Can you provide an example or reference SO or web page? Thanks; – 丶 Limeー来夢 丶 Jul 30 '23 at 16:57
  • The documentation says there's no response for redirects. I haven't used this API, so I can't help further. Personally, I would use method 2 in my comment above. – wOxxOm Jul 30 '23 at 19:38

0 Answers0