Intercept and modify DOM before page is displayed to user

My problem is: can I perform modification on DOM (so: the HTML document that is returned by server) before the page even starts displaying?

Yes, javascript execution starts before the page is rendered the first time. The DOM Parser does notify mutation observers, so you can immediately strip elements as soon as they are added by the parser.

You can register mutation observers even in content scripts loaded with contentScriptWhen: "start" so they should be notified of all elements being added to the tree before they are rendered since the observer notifications are performed in the micro task queue while rendering happens on the macro task queue.

but I wasn’t even able to get it to work: when attached as a pageMod on start the code failed on:
document.getElementById('appcontent').addEventListener('DOMContentLoaded', function(e)

Of course. You should not assume that any element in particular – not even the <body> tag – is already available that early during page load. You will have to wait for them to become available.

And the DOMContentLoaded event can simply be registered on the document object. I don’t know why you would register it on some Element.

(or event prevent any kind of page display before all page was loaded).

You don’t really want that because it would increase page load times and thus reduce responsiveness of the website.

Leave a Comment