JavaScript: Overriding alert()

cllpse picture cllpse · Nov 13, 2009 · Viewed 92.3k times · Source

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?

Answer

Mike Gleason jr Couturier picture Mike Gleason jr Couturier · Nov 13, 2009

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