How can I modify javascript native fetch function from an extension?

20 views Asked by At

I was trying to intercept and modify browser network requests response. To be exact I need to modify responses based on request url. From searching the Internet I came up with a code which is working fine in browser console also with tampermonkey extension.

But when I tried to make it into an extension it is not working. There is no error, even the code is working but in the context of the extension. Like if i fetch something in the extension after this interceptor, that request and response are getting logged. But not working on the site's context.

This is what I came up with the help of Internet:

const originalFetch = window.fetch;

window.fetch = function(url, options) {
  return originalFetch(url, options)
    .then(response => {
      console.log(`Request URL: ${url}`);

      if (response.headers.get('content-type').includes('application/json')) {
        return response.json().then(json => {
          json.modified = true;
          console.log('Modified JSON Response:', json);
          return new Response(JSON.stringify(json), response);
        });
      }

      console.log('Response:', response);
      return response;
    });
};

I am using manifest v3 for the extension.

Thanks in advance. Kindly let me know if this does not clarifies the problem enough.

0

There are 0 answers