1

How would I overwrite the response body for an image with a dynamic value in a Manifest V3 Chrome extension?

This overwrite would happen in the background, as per the Firefox example, (see below) meaning no attaching debuggers or requiring users to press a button every time the page loads to modify the response.

I'm creating a web extension that would store an image in the extension's IndexedDB storage and then override the response body with that image on requests to a certain image. A redirect to a dataurl: I have it working in a Manifest V2 extension in Firefox via the browser.webRequest.onBeforeRequest api with the following code, but browser.webRequest and MV2 are depreciated in Chrome. In MV3, browser.webRequest was replaced with browser.declarativeNetRequest, but it doesn't have the same level of access, as you can only redirect and modify headers, not the body.

Firefox-compatible example:

browser.webRequest.onBeforeRequest.addListener(
    (details) => {
        const request = browser.webRequest.filterResponseData(details.requestId);
        request.onstart = async () => {
            request.write(racetrack);
            request.disconnect();
        };
    },
    {
        urls: ['https://www.example.com/image.png'],
    },
    ['requestBody', 'blocking']
);

The Firefox solution is the only one that worked for me, albeit being exlusive to Firefox. I attempted to write a POC userscript with xhook to modify the content of a DOM image element, but it didn't seem to return the modified image as expected. Previously, I tried using a redirect to a data URI and an external image, but while the redirect worked fine, the website threw an error that it couldn't load the required resources.

I'm guessing I'm going to have to write a content script that injects a Service Worker (unexplored territory for me) into the page and create a page rule that redirects, say /extension-injected-sw.js to either a web-available script, but I'm not too sure about how to pull that off, or if I'd still be able to have the service worker communicate with the extension, or if that would even work at all. Or is there a better way to do this that I'm overlooking?

Thank you for your time!

Basil
  • 23
  • 3
  • Use chrome.declarativeNetRequest.updateDynamicRules to redirect to a `data:` URL generated from the image contents. – wOxxOm Jun 08 '22 at 18:07

0 Answers0