Return confirm in JavaScript

2019-08-18 03:30发布

I have problem with return confirm in Chrome. In Firefox it is ok.

window.onbeforeunload = function() {
    var result = confirm('Really?');

    if(result) {
        console.log('Do something');
    }
}

Any ideas? Thanks!

2条回答
趁早两清
2楼-- · 2019-08-18 03:45

You should return something from beforeunload.

The confirm will be ignored

Since 25 May 2011, the HTML5 specification states that calls to window.showModalDialog(), window.alert(), window.confirm() and window.prompt() methods may be ignored during this event.

see MDN

window.onbeforeunload = function() {
    return 'Date will be lost: are you sure?'; //<= here
}

If you don't return something, the actions within the handler function are executed before the page unloads.

查看更多
来,给爷笑一个
3楼-- · 2019-08-18 03:52

You can't use dialogs (in some browsers) when a user is trying to leave the page. Otherwise you could just put a constant stream of alerts.

查看更多
登录 后发表回答