0

I want to override the style of the alert box when it contains a specific string otherwise to remain as the default one. I've tried to console log it so I can put the if condition but the response is in the following manner:

function alert() { [native code] }

Also when I've tried something different like following:

window.old_alert = window.alert;
window.alert = function(message){
  console.log(message);
  alert(message);
}

I receive the alert message in the console but for an unknown reason it comes over 1000+ times freezing my browser and no popup was present in any way in the window. How this should be approach? Any help or guidance is more than welcomed.

3 Answers 3

3
window.old_alert = window.alert;
window.alert = function(message){
  console.log(message);
  alert(message); //THIS called the new alert recursively, hence the freeze
}

What you wanted to do is:

window.oldAlert = window.alert;
window.alert = function(message) {
    var SpecificString="test";
    if(message.indexOf(SpecificString) >= 0) {
        console.log(message);
    } else {
        window.oldAlert(message);
    }
}

Here's a jsfiddle

0
1

You just caused an infinite recursion with that code!

window.old_alert = window.alert;
window.alert = function(message){
    console.log(message);
    alert(message); // this calls your modified alert causing an infinite recursion
}

What you instead need is:

window.old_alert = window.alert;
window.alert = function(message){
    if(message === "some special string") my_new_alert(message); // call special alert
    else old_alert(message); // this calls the original alert
}
..
my_new_alert = function(message) {
    // modified alert UI
}
1

You can override alert like this but you can't change the default style of the alert box. You'll need to use your own pop up dialog if you need a different style alert.

  var old_alert = window.alert;

  window.alert = function() {
    console.log(arguments[0]);
    return old_alert.apply(this, arguments);
  };

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.