Filtering scripts with filterResponseData

Hi! I have an extension that modifies incoming document HTML in the background. I want to extend this functionality to external scripts, as I can’t seem to access an external script’s content in the contentscript. I have the following code:

function scriptListener(details) {
    let filter = browser.webRequest.filterResponseData(details.requestId);
    let decoder = new TextDecoder("utf-8");
    let encoder = new TextEncoder();
    let str = "";

    filter.ondata = event => {
       str += decoder.decode(event.data, {stream: true});
    };

     filter.onstop = event => {
       //do some modifications to string
       filter.write(encoder.encode(str));
       filter.close();
     };
}

browser.webRequest.onBeforeRequest.addListener( 
    scriptListener,
    {urls: ["<all_urls>"], types: ["script"]},
    ["blocking"]
);

However, I keep getting an uncaught exception: out of memory error. Initially I thought this was due to me decoding with the wrong format, but I tried other formats and it still shows unintelligible strings, and I even tried just doing filter.write(event.data) in filter.ondata, but it still gives me the same error when debugging. Would anyone be able to give some insight into why this is happening? Alternatively, if you know a way to get an external script’s content in the contentscript and modify it there, that would also suffice.

You can not modify a scripts content from a content script, since it is already running once you’d be able to access its contents.