JavaScript: Overriding alert()
Asked Answered
A

12

212

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?
Antler answered 13/11, 2009 at 14:22 Comment(4)
Is that not an infinite loop?Delouse
@Nick - no, it is not. The 'normal' window.alert function will be assigned to window._alert. >After< that the window.alert function is redefined.Teri
@roosteronacid: Your code was semantically and syntactically fine, though contrived, as @paper1337 pointed out...no chance of recursion there lol...in essence you just swapped function bodies with _alert as a sort of expando temp in the first instance.Varga
Aye. I did a roll-back thou, as to not obscure the question :)Antler
D
23

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:

/* new funky alert */
function myFunkyAlert(msg) { 
    /* here goes your funky alert implementation */
    alert("Look ma!\n" + msg);
}

(function(alert) { // anonymous function redefining the "alert"

    /* sample code */
    alert("Hello World!");

})(myFunkyAlert);
Devastation answered 13/11, 2009 at 16:53 Comment(0)
P
216

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:

(function(proxied) {
  window.alert = function() {
    // do something here
    return proxied.apply(this, arguments);
  };
})(window.alert);

You can also bypass the call to the original function if you want (proxied)

More info here: JQuery Types #Proxy Pattern

Peep answered 13/11, 2009 at 14:50 Comment(5)
+1 on the proxy pattern to truly override the func and ensure it doesn't get tampered with!Ludhiana
Ugh! apply() is not available on window.alert in Internet Explorer 8.Antler
I'm sorry to hear that.. apply is a method of the Function object. So they must explicitly restricted it for alert?!Peep
They must've overridden it using the proxy pattern :DLudhiana
Older browsers do not support this and will throw an exception on "window.alert ="Calcar
D
23

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:

/* new funky alert */
function myFunkyAlert(msg) { 
    /* here goes your funky alert implementation */
    alert("Look ma!\n" + msg);
}

(function(alert) { // anonymous function redefining the "alert"

    /* sample code */
    alert("Hello World!");

})(myFunkyAlert);
Devastation answered 13/11, 2009 at 16:53 Comment(0)
H
19

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.');
Heliotrope answered 13/11, 2009 at 16:8 Comment(1)
There could be a danger if your replacement is nonblocking. For example, code which calls alert("Reloading") and then reloads the webpage. The alert text might never be seen by the user.Conative
S
14

As said in many of the other answers, you can just override the function with

window.alert = null

or

window.alert = function(){}

however, this doesn't necessarily override the function on the prototype of the Window constructor (note the capital W), so the hacker can still type:

Window.prototype.alert.apply(window, ["You were hacked!"]);

therefore, you also need to override that function with:

Window.prototype.alert = null

or

Window.prototype.alert = function(){}
Scirrhus answered 23/2, 2014 at 2:44 Comment(3)
This doesn't necessarily override the function in other frames. see jsfiddle.net/18znqbjd/1Hurds
Robert: Yes and for good reasons. Different frames are basically different HTML documents, each with their own "instance" of Javascript.Aorist
Are you sure Window.prototype.alert is still a function in 2017? :PKrell
L
13

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.

Ludhiana answered 13/11, 2009 at 14:34 Comment(0)
K
6

Ladislav.
For IE8 you can redefine alert() like this way

/** 
 * Definition of global attached to window properties <br/>
 */ 
    (function() {
      nalert = window.alert;
      Type = {
          native: 'native',
          custom: 'custom'
      };
    })();

/**
 * Factory method for calling alert(). 
 * It will be call a native alert() or a custom redefined alert() by a Type param.
 * This defeinition need for IE
 */ 
    (function(proxy) {

          proxy.alert = function () {
          var message = (!arguments[0]) ? 'null': arguments[0];
          var type = (!arguments[1]) ? '': arguments[1];

          if(type && type == 'native') {
           nalert(message);
          }
          else {
               document.write('<h1>I am redefiend alert()<br/>Alert say: '+message+'</h1>');
          }     
      };
   })(this);

and call as

alert('Hello, hacker!');
nalert('I am native alert');
alert('Hello, user!', Type.custom);
Keifer answered 22/2, 2011 at 13:58 Comment(0)
F
4

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.

Fugacious answered 13/11, 2009 at 14:44 Comment(0)
A
4

My experience with overriding alert() function is that we once used it to "hack" trial version of JavaScript library that displayed "Please register!" nag screen through alert time to time.

We just defined our own alert() function and voila.

It was for testing purposes only, we bought full version later, so nothing immoral going on here ;-)

Afterburner answered 13/11, 2009 at 14:53 Comment(0)
B
3

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.

Breda answered 2/6, 2020 at 7:18 Comment(0)
O
2

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 =)

Obliteration answered 13/11, 2009 at 14:27 Comment(1)
The Browser to target specifically would be IE6 others would likely be ok with it.Drumfish
K
1

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;
} 
Kirstenkirsteni answered 6/1, 2016 at 0:10 Comment(0)
V
0

When it comes to js browser functions window.alert is pre-eminent and most well known, people who don't know js know alert() -- rest assured it is supported in all browsers in use today and your code snippet is as well. However, I wouldn't override (well this is more like refactoring rather than override in the OOP sense) alert() for a particular use case as yours because when you actually need to use alert() with no template, and you probably will, then you'll need another non-alert function to do so.

Varga answered 13/11, 2009 at 14:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.