如何根据文本有条件地防止警报?

How to prevent Alerts conditionally based on the text?

我有以下情况,我需要防止在消息为 "hi" 时出现警告框。对于所有其他情况,应该会出现警告框。

window.alert = function(text) {
  if(text=='hi') {
    console.log('Prevented alert Box');
  } else {
    // Continue displaying Alert. 
  }
};

我不确定这里的正确方法。任何帮助是极大的赞赏。提前致谢。

您需要保留对旧警报的引用..

例如

var old_alert = window.alert;

window.alert = function(text) {
  if(text=='hi') {
    console.log('Prevented alert Box');
  } else {
    old_alert(text);
  }
};

alert("hi");
alert("there");

通过执行以下操作保存 alert 的原始版本:

window.originalAlert = window.alert;

然后像上面那样重新定义警报:

window.alert = function(text) {
  if(text=='hi') {
    console.log('Prevented alert Box');
  } else {
    window.originalAlert(text); 
  }
};