1

I have many JavaScript functions for a program, all of which contain alerts notifying the user of certain things. I wanted to give the user the option to ban all of those alerts, without having to rewrite all of the functions without the alerts. Is there a way to ban alert? Maybe something like this:

<button onclick = "alertBan()">Alert Ban</button>
function alertBan(){
     alerts = false;
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • quick & dirty: `const alertBan = ()=>{};` override the `alertBan` function – Marc Aug 09 '20 at 20:13
  • 2
    Does this answer your question? [JavaScript: Overriding alert()](https://stackoverflow.com/questions/1729501/javascript-overriding-alert) – klediooo Aug 09 '20 at 20:14

2 Answers2

3

Just assign an empty function to alert.

function alertBan(){
     alert = function(){};
}

If you might need to reenable alerts later on, you can store window.alert in a variable when the page loads.

const oldAlert = alert;
function alertBan(){
     alert = function(){};
}
function enableAlerts(){
    alert = oldAlert;
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

Store the original alert for perhaps later use. Replace the alert through empty function or with setted parameter to write on console.
If need the normal alert back take the stored one back.

alertOrig = alert;
function alertBan(consoleLog){
    alert = function(e) {
        if (consoleLog) console.log(e);
    }
}

function alertEnable(){
   if ( alertOrig )
       alert=alertOrig;
}

alertBan();
alert('No console + no alert');

alertBan(true);
alert('With console');

alertEnable();
alert('Normal alert');
Sascha
  • 4,576
  • 3
  • 13
  • 34