Edwin Thomas
Edwin Thomas

Reputation: 486

Disable alert Message

How can I disable certain alert on the page and allow others?

I tried With this code:

window.alert = function ( text ) {
   console.log(text); 
   if(!text.includes("rambo"))
      alert("rambo"); 
};

This won't work because it calls alert again and not the alert.

I need to use javascript alert( not any other libraries)

Upvotes: 6

Views: 3226

Answers (4)

Niladri Basu
Niladri Basu

Reputation: 10624

If you don't wan't to pollute global namespace or use an IIFE, why don't you simply wrap window.alert in another function like this:

function myCustomAlert(message) {
  return message.includes('rambo') ? 
     window.alert(message)
   : false;
}

myCustomAlert("This message won't be shown!");

myCustomAlert("This message will be shown because it contains rambo");

Upvotes: 1

Birbal Singh
Birbal Singh

Reputation: 1072

You can store old alter in variable

var ar = alert;
window.alert = function(text) {
    console.log(text);
    if (!text.includes("rambo"))
        ar("rambo");
    return true;
};

alert('dfs');

Upvotes: 2

Nisarg Shah
Nisarg Shah

Reputation: 14561

The other two answers are mostly correct, but they pollute the global namespace by creating a new reference to window.alert. So I would suggest wrapping this in an IIFE:

(function() {
  var nativeAlert = window.alert;
  window.alert = function(message) {
    if (message.includes("test")) {
      nativeAlert(message);
    }
  };
}());

alert("Hello"); // Doesn't show up.
alert("Hello test"); // Works.

nativeAlert("test"); // Throws an error.

You could go a step further an create an alert function generator that creates an alert object using a predicate:

function alertGenerator(predicate) {
  if (typeof predicate === "function") {
    return function(message) {
      if (predicate(message) === true) {
        window.alert(message);
      }
    }    
  } else {
    return undefined;
  }
}

// Create an alert generator that requires the word "test" in it:
var testAlert = alertGenerator(t => t.includes("test"));
testAlert("Hello"); // Doesn't show up.
testAlert("Hello test"); // Works.

// Create an alert generator that requires the word "Hello" in it:
var helloAlert = alertGenerator(t => t.includes("Hello"));
helloAlert("Hello"); // Works.
helloAlert("Hello test"); // Works.
helloAlert("Test"); // Doesn't work.

Upvotes: 4

CertainPerformance
CertainPerformance

Reputation: 371198

Save a reference to the old window.alert first.

const oldAlert = window.alert;
window.alert = function ( text ) {
  console.log(text); 
  if(!text.includes("rambo"))
    oldAlert(text); 
  return true;
};

window.alert('ram');
window.alert('rambo');

Upvotes: 15

Related Questions