noscript icon indicating copy to clipboard operation
noscript copied to clipboard

I found an easier way to block script elements in Web Extensions using MutationObserver!

Open cookiengineer opened this issue 4 years ago • 1 comments

Hey there,

after having used noscript for a very long time, I am now building my own web extension that aims to ease up web scraping tasks. This isn't intended to be a shameless ad, I promise. I just wanted to let you know of this way, so that maybe you can speed up noscript, too.

Today I found a way to block script elements from loading that doesn't necessarily rely on the Content-Security-Policy and instead uses a MutationObserver on the document.documentElement ( node) as a content script that is injected at document_start.

The MutationObserver then simply blocks all addedNodes[] that have a node.tagName == "SCRIPT" (or are conditional comments) and removes them immediately from their parentNode. This leads to no JS being executed at all, and also doesn't load anything via HTTP. Additionally this ensures that

Afterwards I had to add some cleanup scripts on document_end that removes all <a href="javascript:..."> link attributes so that there were no console errors all the time due to undefined functions being called.

Maybe this helps you, too?

cookiengineer avatar Apr 20 '21 10:04 cookiengineer

Mutation observer is not guaranteed to run before elements are added into DOM. In fact it was designed to work exactly after they are added in order not to block. In Firefox working on ResourceOverride I finally had to intercept traffic and edit HTML to edit the stuff reliably.

KOLANICH avatar Apr 20 '21 12:04 KOLANICH