检测页面上是否显示警报或确认

有没有办法使用JavaScript或jQuery来检测是否显示确认或警告框?

如果你想在alert()触发时运行一些代码,你可以尝试这样的事情:

我只在Chrome中测试过,所以我不确定是否支持浏览器。

示例: http //jsfiddle.net/Q785x/1/

 (function() { var _old_alert = window.alert; window.alert = function() { // run some code when the alert pops up document.body.innerHTML += "
alerting"; _old_alert.apply(window,arguments); // run some code after the alert document.body.innerHTML += "
done alerting
"; }; })(); alert('hey'); alert('you'); alert('there');

当然,这只允许您在警报之前和之后运行代码。 正如@kander所说,在显示警报时,javascript执行停止。

不,那里没有。 您可以检查confirm命令的返回值confirmtruefalse但是您无法检查是否存在视觉效果。

这些东西是浏览器的一部分,不是DOM的一部分。 我确定有一个适用于IE的脏黑客,因为它是Windows操作系统的一个卑鄙的孩子。

如果你想……你可以这样做

 (function () { // remember the normal alert var oldAlert = (function(){ return this.alert; }()), oldConfirm = (function(){ return this.confirm; }()); // inject ourself into the window.alert and window.confirm globals alert = function (msg) { oldAlert.call(document, msg); document.onAlert(msg); }; confirm = function (msg) { var result = oldConfirm.call(document, msg); document.onConfirm(msg, result); return result; }; // these just chill and listen for events document.onAlert = function (msg) { window.console && console.log('someone alerted: ' + msg); }; document.onConfirm = function (msg) { window.console && console.log('someone was asked: ' + msg); window.console && console.log('and they answered: ' + (msg ? 'yes' : 'no')); }; }()); 

这样做的缺点是

如果要检测这些是否被阻止。 您将不得不使用您将不相信的消息做自己的事情,但覆盖本机警报/确认。

 window.nativeAlert = window.alert; window.alert = function (message) { var timeBefore = new Date(); var confirmBool = nativeAlert(message); var timeAfter = new Date(); if ((timeAfter - timeBefore) < 350) { MySpecialDialog("You have alerts turned off, turn them back on or die!!!"); } } window.nativeConfirm = window.confirm; window.confirm = function (message) { var timeBefore = new Date(); var confirmBool = nativeConfirm(message); var timeAfter = new Date(); if ((timeAfter - timeBefore) < 350) { MySpecialDialog("You have alerts turned off, turn them back on or die!!!"); } return confirmBool; } 

显然我已将时间设置为3.5毫秒。 但经过一些测试后,我们只能在大约5毫秒的时间内点击或关闭对话框

确认和警告框是阻止事件 – 在显示这些事件时,Javascript代码将暂停执行。 所以不 – 据我所知,你无法检测到当前是否正在显示一个。

要添加到@ user113716的答案,您可以依靠时间。 我假设如果确认对话框花了不到200毫秒,它就会被浏览器阻止。 如果确认对话框被阻止,则返回true(默认情况下,它返回false,代码在TypeScript中)。

  let oldConfirm = window.confirm; window.confirm = (msg) => { let time = new Date().getTime(); let conf = oldConfirm(msg); return new Date().getTime() - time > 200 ? conf : true; }