Link to home
Start Free TrialLog in
Avatar of GE_Dave
GE_DaveFlag for United States of America

asked on

Intercept (and examine) windows alert message in Javascript

I am trying to intercept the Windows Alert Message and decide whether to modify it (or to even to display it).
I have been working with the  code below, but it is displaying the  Alert first, then acting on "do something here".
I need to examine the Alert Message and either display as is, display a modified version or prevent it's display altogether.
Note: The solution only needs to work in Chrome
Thank you

(function() {
  var proxied = window.alert;
  window.alert = function() {
    // do something here
    return proxied.apply(this, arguments);
  };
})();
Avatar of Rob
Rob
Flag of Australia image

window.alert = function(e) {
    e.preventDefault();
    // do something here
    return proxied.apply(this, arguments);
}
You may also need:

e.stopPropagation();
Avatar of GE_Dave

ASKER

Thank You.
I will experiment with this later in the day...
ASKER CERTIFIED SOLUTION
Avatar of Rob
Rob
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of GE_Dave

ASKER

Thank you.
I have worked with that code as well.  However, it assumes that I am generating the alert (requires fallback).
My goal is to stop an erroneous Alert message from being shown, by intercepting, checking the message and blocking it if the a specific message).  I am doing this because it will be several weeks before the code without the erroneous Alert will be pushed to production.
so you need to include the code I've posted before anything else on your page. Then it will work as any call to "alert(...)" will be intercepted by your function.
Avatar of GE_Dave

ASKER

Thank you again.  
I was over complicating it.

window.old_alert = window.alert;

window.alert = function(message){
  var myTestString = 'Bad Alert';
  if (message == myTestString){
    return;
  }
  old_alert(message);
};

Open in new window

Good to hear. Thanks for the points