window.onbeforeunload handling ok and cancel options

北城余情 提交于 2019-12-13 04:43:28

问题


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 pressed , then make an event call and continue with the "ok"/"cancel" option.


回答1:


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;



回答2:


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.




回答3:


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
}


来源:https://stackoverflow.com/questions/5579326/window-onbeforeunload-handling-ok-and-cancel-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!