views:

65

answers:

2

In javascript or jquery I need to add an alert when the user clicks on the browser back button that has an ok/cancel button model, but instead of "Ok" it should say Leave and instead of Cancel it should say Stay. Thanks

+1  A: 

You can't control the confirmation dialog button text, it's a hard coded feature of confirm() and is whatever the browser has...not much you can do about it.

For the actual display you can use window.onbeforeunload, but it won't be specific to the back button, any action leaving the page will trigger this, for example:

window.onbeforeunload = function() {
  return "Are you sure you wish to leave this delightful page?";
}
Nick Craver
I don't think `window.confirm` really has anything to do with it. It's just that both the `confirm` and `onbeforeunload` dialog boxes happen (in most browsers) to have OK and Cancel, and the underlying GUI code may be similar.
Matthew Flaschen
Are you sure you wanted to try to call `confirm` in your `onbeforeunload`? Standard practise is to just return the string, and let the browser do the prompting.
RichieHindle
@Matthew - Sorry if I was unclear...my point was whatever the buttons are, you can't change that "Ok" or "Cancel" or whatever the browser has...which seems to be what the OP is after.
Nick Craver
Do you know how to do it without the custom button labels?
sway
@RichieHindle - That works as well, the prompt was just an example, my point was more that the OP may want to rethink the approach, since you can't narrow it to *only* the back button, nor can you change the prompt button text.
Nick Craver
@sway - The example in the question, or as Richie alluded to, `return "Are you sure you wish to leave this delightful page?";` also works, but it won't be back button specific, e.g. you'll want to unbind it when going to a place that you *don't* want to prompt, on form submission, etc.
Nick Craver
I don't think `confirm` does work. In Firefox at least, you can execute confirm in the `onbeforeunload` handler, but I don't think you can block the page change based on a `confirm` result in any browser.
Matthew Flaschen
Ok so I did the window.onbeforeunload and in Chrome got this dialog, so I guess it's a chrome thing. http://cl.ly/265934776cc780ed873d
sway
@Matthew - Ah didn't realize FireFox prevented that, updated with a simple return string...I tend to abhor these dialogs, so don't use them often enough to know *every* quirk :)
Nick Craver
A: 

And this kind of alert sucks. ;-)

Malartre