开发者

window.onbeforeunload handling ok and cancel options

I have a window.onbeforeunload function which generates the default message:

"Are you sure you want to navigate away from this page...." .

If we click on OK we are redirected to a new link and if we press cancel we are redirected back to the same page.

I want to save some data from the page when we press OK and move away from the page. How can we know if OK or cancel has been presse开发者_StackOverflowd, then make an event call and continue with the "ok"/"cancel" option.


A possible approach might be to hook into the onunload event as well, and if that handler is called, you know that the user chose OK.

In onbeforeunload, set a timeout callback that is called some time afterwards (e.g. 1 second), and if it is called, the user might have selected Cancel.

Not sure how safe this is regarding race conditions though.


function leavePage() {
    //do your thing like saving the data in the session
    return "Some data entered may be lost."; //a text needs to be returned
}

window.onbeforeunload = leavePage;


Are you using JavaScript 'confirm' dialog?

if(confirm("Are you sure you want to navigate away from this page....")) {
    // OK was pressed
} else {
    // Cancel was pressed
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜