Has anyone got any experience with overriding the alert()
function in JavaScript?
- Which browsers support this?
- Which browser-versions support this?
- What are the dangers in overriding the function?
Has anyone got any experience with overriding the alert()
function in JavaScript?
There are no dangers in Overring alert function. Every browser supprts it.
for example:
Although most browsers support overriding it, be careful with what you're doing with it.
Since the default alert box blocks the execution thread, some libraries that rely on this behaviour might not work anymore (at best).
You should be a good citizen and avoid touching the native API. If you do, you could break things up, when using 3rd party code.
Yet, if you want to redefine the alert behaviour in a specific context, you could enclose it with an anonymous function, like this:
It's definitely "supported". It is your web page, you do whatever you want to with it.
I already did this to track analytics events without modifying a library but by sneaking into events.
Use the proxy pattern:
You can also bypass the call to the original function if you want (proxied)
More info here: JQuery Types #Proxy Pattern
Ladislav.
For IE8 you can redefine alert() like this way
and call as
As said in many of the other answers, you can just override the function with
or
however, this doesn't necessarily override the function on the prototype of the
Window
constructor (note the capitalW
), so the hacker can still type:therefore, you also need to override that function with:
or