Overwriting native functions in javascript
Wednesday, 8 April 2009
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.
window.alert = function(native) {
var counter = 0;
return function(str) {
native(str);
if(counter > 10) {
window.alert = null;
}
counter++;
}
}(window.alert);
No. 1 — April 8th, 2009 at 12:23 pm
Yes, it can be beaten quite easily:
http://sla.ckers.org/forum/read.php?2,15812,27520#msg-27520
No. 2 — April 8th, 2009 at 12:29 pm
@Giorgio
Nice! Just another windmill war again then 🙁
No. 3 — April 12th, 2009 at 3:42 am
This code is great, is free to use?
No. 4 — April 12th, 2009 at 9:51 am
@Ehsun
Yeah completely free