是否有一种使用JavaScript或jQuery来检测确认框或提示框是否正在显示的方法?
是否有一种使用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 += "<br>alerting";
_old_alert.apply(window,arguments);
// run some code after the alert
document.body.innerHTML += "<br>done alerting<br>";
};
})();
alert('hey');
alert('you');
alert('there');
当然,这只能让您在警告框弹出前后运行代码。正如@kander所指出的那样,在显示警告时JavaScript执行被暂停。没有这样的方法。您可以检查confirm
命令的返回值是否为true
或false
,但无法检查其是否显示出来。
这些属于浏览器而非DOM的一部分。我确定有一种针对IE的肮脏黑客方法可以实现,因为它是Windows操作系统的一个杂交儿。
alert
或confirm
之前注入自己的处理程序(请参见下面的答案),或2)设置一个函数间隔(setInterval
)来了解UI线程上次解锁的时间(虽然长时间的滞后不一定只是由于alert()
或confirm()
,但可能足够说明问题)。 - Dan Beamwindow.alert
函数,而它不在 DOM 中,超出了您的控制范围。 - Raynos如果你想这样做,你可以...
(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'));
};
}());
alert()
和 confirm()
的使用,哈哈。除了@user113716的回答,你还可以借助时间来判断。我认为如果确认对话框的响应时间小于200毫秒,那么它就被浏览器阻塞了。下面的代码是基于TypeScript编写的,默认返回false,如果确认对话框被阻塞则返回true。
let oldConfirm = window.confirm;
window.confirm = (msg) => {
let time = new Date().getTime();
let conf = oldConfirm(msg);
return new Date().getTime() - time > 200 ? conf : true;
}
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毫秒左右点击或关闭对话框。