JavaScript’s DOM Vanishing Act
Here’s a wonky little JavaScript that stood out while doing a review of a malvertising payload:
(function (a) {
return a && a.parentNode && a.parentNode.removeChild(a)
})(document.currentScript)Let’s break it down a little:
The Node.removeChild() method removes a child node from the DOM. Returns removed node.
document.currentScript — Returns the <script> element whose script is currently being processed.
So could it be that it’s possible for a script to remove the tag that invoked it and stay running? It turns out the answer is yes. If at first glance this is a bit surprising, that’s perhaps because there is little need to ever do so unless perhaps one has something to hide.
The fact remains that the DOM is stateful and mutable while JavaScript itself runs in memory. The two are not tethered to each other by any means. It’s easily overlooked at times that the two are entirely separate entities.
Let’s test it out:
And now for the proof:
Looks like everything went according to plan! Our script executed a document.write, removed itself from the DOM, yet was still able to continue its execution and execute the next document. write.





