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

Ugg*_*s2k 19 javascript jquery alert

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

use*_*716 21

如果你想在发生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');
Run Code Online (Sandbox Code Playgroud)

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


Ray*_*nos 5

不,那里没有.您可以检查confirm命令的返回值是否确实true或者false您无法检查是否存在视觉效果.

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

  • +1,因为你的第二段几乎肯定是真的. (4认同)

Dan*_*eam 5

如果你愿意,你可以这样做...

(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'));
    };

}());
Run Code Online (Sandbox Code Playgroud)

这样做的缺点是