通过JavaScript捕获并更改默认警报()行为

Capture and Change default alert() behavior via JavaScript

本文关键字:行为 默认 JavaScript 通过      更新时间:2023-09-26

我很久以前就做过这样的事情,我捕获了警报,阻止了默认的基于浏览器的警报框弹出,并将其替换为一种或另一种模式。然而,我已经很久没有这么做了,我无法从我的旧代码中找到任何关于我是如何做到这一点的参考,目前我也无法通过谷歌找到任何相关的内容。所以…我希望这里有人能帮助我,帮助我。我什么都没试过,所以别问你我试过什么了。除了花最后一个小时左右的时间在谷歌上搜索不同的短语,寻找与我模糊记忆中相似的代码片段外,我还是两手空空。我知道,这是一个质量很差的问题,但同时我相信其他人也会很感激知道答案。

在这种情况下,我只想捕获将触发alert()框的事件,并将其中的消息传递给另一种通知变体。目前,我正在appmobi中与其他几个人一起做一些工作,我想拍摄alert(),然后使用

AppMobi.notification.alert(message,title,buttontext);作为alert() 的默认操作

您可以简单地覆盖警报方法:

window.alert = function(msg) {
   // whatever you want to do with 'msg' here
};

请注意,这不会具有常规alert 的阻塞行为

window.alert = function(message,title,buttontext) {
   AppMobi.notification.alert(message,title,buttontext); 
};

正如其他人所指出的,它可以被重写——只需记住AppMobi.notification.alert需要三个参数。如果它有后备默认值,我不会感到惊讶,但安全总比抱歉好:

//alert is a native code function that we may need elsewhere
window.legacyAlert = window.alert;
window.alert = function(_msg) {
  AppMobi.notification.alert(_msg, 'Alert', 'OK');//or whatever
};

这将全局覆盖该方法。或者,您可能需要使用闭包仅在代码的某些部分覆盖它:

alert('this is a vanilla js alert');
(function(alert) {
    alert('this alert has been overridden');
})(AppMobi.notification.alert);
alert('this is another vanilla js alert');

扭曲