DOM freezing for JavaScript: overriding DOM modification functions as no-ops
I am writing a piece of code that requires a DOM
website to remain frozen when arbitrary JavaScript runs. Changing the attributes is ok, but I can't change anything from the original tag structure on the page!
I know that JavaScript has a base number of functions that can change DOM
:
appendChild( nodeToAppend )
cloneNode( true|false )
createElement( tagName )
createElemeentNS( namespace, tagName )
createTextNode( textString )
innerHTML
insertBefore( nodeToInsert, nodeToInsertBefore )
removeChild( nodetoRemove )
replacechild( nodeToInsert, nodeToReplace )
My initial thought was to simply overwrite these functions as no ops:
>>> document.write('<p>Changing your DOM. Mwwhaha!</p>')
>>> document.write = function() {}
>>> document.write('<p>No-op now!</p>')
While this is easy on an object document
, modification functions DOM
can be called from many different JavaScript objects! If I could overwrite these functions at the top level, perhaps it would work?
Update from sktrdie:
>>> HTMLElement.prototype.appendChild = function(){}
>>> $("a").get(0).appendChild(document.createElement("div"))
# Still works argh.
>>> HTMLAnchorElement.prototype.appendChild = function(){}
>>> $("a").get(0).appendChild(document.createElement("div"))
# No-op yeah!
So, it would seem that I could just collect the constructors of all the elements DOM
and run them by putting no-ops, but that still seems pretty messy ...
How can I protect DOM
against modification from arbitrary JavaScript?
source to share
While this is really hackish, the only way to maintain the current DOM structure is to keep a snapshot of the DOM and check it periodically.
//place in anonymous function to prevent global access
(function() {
//storing the whole DOM as objects would be ideal, but too memory intensive, so a string will have to do.
var originalDOM = document.body.innerHTML;
var checkDOM = function() {
if (document.body.innerHTML != originalDOM) document.body.innerHTML = originalDOM
//check that the code is running
if (arbitraryCodeIsRunning) setTimeout("checkDOM", 100);
}
checkDOM();
})();
Probably not what you're looking for, but after some testing, this is the only way I can think of maintaining the DOM structure independently.
source to share