I had a similar problem: my webapp needs know the exact representation of the DOM tree.
Grammarly's extension, however, adds random bits of custom HTML into the DOM tree. I solved the problem by disallowing grammarly, or anything, from modifying the HTML.
I use code similar to @jbranj. But I remove any added HTML from the page. I see a minor slow down on first click into the textarea on safari but it's fine otherwise.
var observer = new MutationObserver(function (mutationsList, observer) {
for (let mutation of mutationsList) {
if (mutation.type === 'childList') {
for (let node of mutation.addedNodes) node.remove()
}
}
})
I run observer.observe(document, { attributes: false, childList: true, subtree: true })
when I want to prevent HTML additions. And observer.disconnect()
when I want to allow it so I can modify the DOM myself.
(I'm not entirely sure why but both childList
and subTree
need to be true when you enable the observer.)
Edit:
Because some anti-virus software can hang the browser if you straight out refuse to let them inject scripts in your html:
var added_nodes = []
var observer = new MutationObserver(function (mutationsList, observer) {
for (let mutation of mutationsList) {
if (mutation.type === 'childList') {
for (let node of mutation.addedNodes) added_nodes.push(node)
}
}
})
Then later added_nodes.forEach(n => n.remove())
to remove all the injected tags.