Right way to intercept (text/plain) requests?

124 views
Skip to first unread message

Michael Carmack

unread,
Feb 27, 2024, 5:26:21 AM2/27/24
to Chromium Extensions
I feel like this has a simple solution but the web has me running in circles, with a lot of conflicting information due to differences between manifest versions.

Basically, I just want the extension to grab any text/plain resource that is destined for the main_frame (i.e. not a xmlhttprequest) and prevent the browser from doing its default behavior of generating the <pre> content. Instead it should run the script content.js instead.

A minimal manifest.json that is working aside from not triggering at the right time is here:

{
    "manifest_version": 3,
    "name" : "text/plain interceptor",
    "permissions":["storage","webRequest"],
    "host_permissions":["<all_urls>"],
    "content_scripts": [{"matches": ["<all_urls>"],"js": ["content.js"]}]
}

This works great, but it doesn't run until the browser first renders the entire text file into a <pre> tag, which gets quite slow for large files. And it's entirely unnecessary because I'm building the entire <html> doc from scratch and throwing away what the browser generates anyway.

So what magic is required to stop the browser from doing anything at all with the content, and just letting the extension deal with it?


wOxxOm

unread,
Feb 27, 2024, 9:16:50 AM2/27/24
to Chromium Extensions, Michael Carmack
Chrome extensions never had such capability. Firefox can do it via filterResponseData. The workaround for Chrome is to run the content script earlier by adding "run_at": "document_start" and check document.contentType inside the content script.

wOxxOm

unread,
Feb 27, 2024, 9:25:19 AM2/27/24
to Chromium Extensions, wOxxOm, Michael Carmack
Depending on how you process these documents it might be better to use chrome.webRequest.onHeadersReceived, check Content-Type header, and inject the content script explicitly using chrome.scripting.executeScript with injectImmediately:true.

To avoid the flash of unstyled text in big documents your content script can set document.documentElement.style.display = 'hidden' or something like that while it processes DOM.

Reply all
Reply to author
Forward
0 new messages