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)
Open Chrome DevTools. Press Control+Shift+P or Command+Shift+P (Mac) to open the Command Menu. Start typing javascript , select Disable JavaScript, and then press Enter to run the command. JavaScript is now disabled.
Select the object from the Object Type drop down. In this case we are going to select the Cisco Networking Switch object. Now select the Alert Definition you want to disable and chose the Actions drop down, then choose State – Disable, then Save. This will disable that particular alert in the selected policy.
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');
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With