4

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
prateek
  • 41
  • 1
  • 2

3 Answers3

1

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.

Arc
  • 11,143
  • 4
  • 52
  • 75
  • That does work, however, 1 second is too short making it an absolute horrible way of knowing whether the user decided to cancel. I had to use a timeout of 5 to 10 seconds to make sure I get it right. – Alexis Wilke Jan 19 '15 at 13:07
0
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;
rlcabral
  • 1,496
  • 15
  • 39
  • I want to save data only when I press "ok" and not when i press "cancel". In your solution the data will be saved in both the cases. – prateek Apr 07 '11 at 10:31
-1

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
}
Jim Blackler
  • 22,946
  • 12
  • 85
  • 101
  • 2
    The dialog is probably generated by the browser. https://developer.mozilla.org/en/DOM/window.onbeforeunload – Arc Apr 07 '11 at 10:13
  • 1
    You cannot use the `confirm()` function in the `onunloadbefore()`. It won't work. The browser creates a confirmation dialog when you return a string. – Alexis Wilke Jan 19 '15 at 12:18