Has anyone got any experience with overriding the alert()
function in JavaScript?
All JavaScript implementations in modern browsers support overriding.
The dangers are quite simply, that you would drive other team members absolutely crazy by overriding commonly known functions such as alert().
So unless you are overriding functions as a tool to perhaps debug or hack existing code in some way, I don't see any reason to do it. Just create a new function.
There are no dangers in Overring alert function. Every browser supprts it.
for example:
// function over riding. Redirecting to Console with Firebug installed.
function alert(message) {
console.info(message);
}
alert('This is an override.');
I think every Javascript implementation will support this, and there is no danger involved with it. It's commonly done to replace the plain OS-styled alert boxes to something more elegant with HTML/CSS. Doing it this way means you don't have to change existing code! The fact that it is possible makes Javascript awesome.
A quick hack that I do to find where the alerts are coming from, is to go to console and then enter this
function alert(message) {
console.info(message);
debugger;
}
I have faced a requirement to show a default message along with the actual alert messages. This is how I managed to do it.
const actualAlertFunc = window.alert;
window.alert = function(msg) {
actualAlertFunc('some default message '+ msg);
}
I have tested it on chrome. I am not sure whether its a good practise, but it serves the purpose.
It sure works in firefox and ie8. I can't see that there'd be any browser it wouldn't work in. This is pretty much fundamental of how javascript works, even though one don't often see it used with native functions like that =)