window.onbeforeunload handling ok and cancel options
Asked Answered
M

3

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.

Muskellunge answered 7/4, 2011 at 10:4 Comment(0)
M
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.

Maricela answered 7/4, 2011 at 10:17 Comment(1)
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.Huerta
S
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;
Summertree answered 7/4, 2011 at 10:15 Comment(1)
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.Muskellunge
K
-2

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
}
Kaceykachina answered 7/4, 2011 at 10:8 Comment(2)
The dialog is probably generated by the browser. developer.mozilla.org/en/DOM/window.onbeforeunloadMaricela
You cannot use the confirm() function in the onunloadbefore(). It won't work. The browser creates a confirmation dialog when you return a string.Huerta

© 2022 - 2024 — McMap. All rights reserved.