问题
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