views:

42

answers:

1

i want to pop up a dialog before a html page is unloaded asking to unload page or not if yes is selected then unload continues else if no is selected unload event is canceled...

+3  A: 

You can't set the text to "yes"/"no" (it'll be "Ok"/"Cancel" in most browsers), but you can prompt (be careful when using this) when leaving the page in any manner using window.onbeforeunload, like this:

window.onbeforeunload = function() {
  return "Are you sure you wish to leave the page?";
}

Only use this if you have a good reason, don't annoy your users. That being said, this will prompt when leaving the page, that includes history back, forward, refresh, closing the window/tab, clicking a link to navigate away or submitting a form, etc. So you'll probably want to call this when going somewhere that shouldn't prompt:

window.onbeforeunload = null;

For example, submitting a form of information, you'd want to prompt when leaving/losing the data, but not when actually submitting it.

Nick Craver
@suraj: For an example, start typing an answer below and then try to leave the page. :-) StackOverflow does exactly what Nick describes.
T.J. Crowder
@Nick: *"So you'll probably want to call this when going somewhere that shouldn't prompt..."* Or use a flag or check in the function, rather than disconnecting it. If the function doesn't return a string, it doesn't prompt the user.
T.J. Crowder
@suraj: Example: http://jsbin.com/aquse4
T.J. Crowder
@TJCrowder - There was *some* issue with this I can't remember for the life of me, but ran into it before, where detaching was always the safe route. If I think of it today I'll come back and update, I do remember it was a rare edge case though, possibly in just 1 or 2 browsers (there's security, or annoyance, code governing what's allowed to be used in that function in various browsers).
Nick Craver