Photo by Dmitry Demidko on Unsplash

Preventing a bank robbery by overriding native prototypes in JavaScript

If you haven’t read my previous article and are not familiar with what overriding native prototypes means, check it out over here

Upon first glance at the title of this article you may be thinking, preventing a bank robbery with JavaScript? How does that work?

I’d like to compare the DOM of your website to your bank account. It’s your private property and you should be the one deciding how and when it should be used. In this article, I’d like to examine the available options that are available to developers in order to empower them to manage the DOM.

The option that jumps out at first is using a MutationObserver. A quick look at all developers’ favorite resource says the following about Mutation Observers

The MutationObserver interface provides the ability to watch for changes being made to the DOM tree.

Using a MutationObserver we can be notified when elements have been added to the DOM. We are also provided which elements have been added to the DOM. What we could then do is:

  1. MutationObserver handler is triggered with the nodes that were added

The issue with this solution becomes apparent on the 4th step. By the time the mutation observer is notified of the DOM change, it’s too late. The “robber” has already been added to the DOM.

This then brings us to the solution that you came here for.
Overriding. Native. Prototypes. 🥳

For a quick recap, overriding native prototypes involves redefining a method or property that exists upon the prototype of a native object. For example:

Array.prototype.push = ()=> {console.log('overridden')}
Array.prototype.filter = ()=> {console.log('overridden')}
Function.prototype.call = ()=> {console.log('overridden')}

Once any of the above code has been run, all subsequent calls to any of those methods will print the defined log statement.

So how does this relate to intercepting appending nodes to the DOM you ask? Well, one of the ways elements can be appended to the DOM is by using the appendChild method. But where does this method come from? A quick google search shows me that it exists on the Node prototype Node.prototype.appendChild. Knowing this, creating a solution should be fairly easy.

Let’s go over how this solution works.

  1. Line 2 Store a reference to native appendChild method

An obvious advantage of this approach is that the “robber” is never actually appended to the DOM. The disadvantage of this approach compared to the MutationObserver is that there are many more ways to add elements to the DOM that all need to be overridden.

I hope that this article has been informative. Stay tuned for the next one.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store