Overwriting native functions in javascript

Back to articles

hackvertor

Author:

Gareth Heyes

@hackvertor

Published 16 years 5 months ago
Published: Wed, 08 Apr 2009 09:05:45 GMT
Updated: Sat, 22 Mar 2025 15:38:13 GMT
Read time: ⏱️ 2 min read

I research a lot of Javascript as part of my job and I've been toying with the idea of a perfect native function overwrite. The idea is that you can still call the native function and have control over it but once it's been defined it cannot be modified only destroyed.

My idea was to redefine the alert function and to remove it once it reaches a certain limit, in order to avoid infinite prompts. I think I've been successful but I'm sure someone will point out if I haven't. It works by storing the native function in a closure and holds the reference within it's parent. The child function is then returned with two private variables the native function call and a counter. Because they are private variables they shouldn't be available in the global scope and so only the parent of the the child function should have access to them.

This code is based on the assumption that it is run first before any other Javascript, so you can modify it after it's been executed but you should no longer have access to it's native code.

<pre lang="javascript"> window.alert = function(native) { var counter = 0; return function(str) { native(str); if(counter > 10) { window.alert = null; } counter++; } }(window.alert); </pre>

Back to articles