如果包含特定字符串,则覆盖警报框

Override alert box when contains specific string

本文关键字:覆盖 包含特 字符串 如果      更新时间:2023-09-26

当警报框包含特定字符串时,我想覆盖它的样式,否则将保留为默认字符串。我试着用控制台记录它,这样我就可以设置if条件,但响应如下:

function alert() { [native code] }

同样,当我尝试了一些不同的东西,比如:

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

我在控制台中收到警报消息,但由于未知原因,它冻结了我的浏览器1000多次,窗口中没有任何弹出窗口。应该如何处理?任何帮助或指导都是非常受欢迎的。

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

你想做的是:

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

这是一个jsfiddle

您刚刚用该代码引发了一个无限递归!

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

相反,您需要的是:

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
}

您可以像这样覆盖alert,但不能更改警报框的默认样式。如果你需要不同风格的提醒,你需要使用自己的弹出对话框。

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