If the code below is run in DevTools or in the browser's address bar, the h1 element will be inserted at the end of a website's page.
const elm = document.createElement('h1')
const txt = document.createTextNode('New text')
elm.appendChild(txt)
document.body.appendChild(elm)
Can any site prevent this from happening using, for example, MutationObserver?
A simple way would be to overwrite the appendChild on document.body so that calling it does nothing.
// page code:
document.body.appendChild = () => {};
// user code:
const elm = document.createElement('h1')
const txt = document.createTextNode('New text')
elm.appendChild(txt)
document.body.appendChild(elm)
A MutationObserver would work too - observe the document.body for childNode changes, and call .remove() on all of the added nodes (available inside the callback's parameter).