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
Asked
Active
Viewed 1.3k times
6
-
1See [ How can I override the OnBeforeUnload dialog and replace it with my own? ](http://stackoverflow.com/questions/276660/how-can-i-override-the-onbeforeunload-dialog-and-replace-it-with-my-own). The bottom line is that the only flexibility for this dialog is adding a string. This is for security reasons. – Matthew Flaschen Sep 09 '10 at 22:53
1 Answers
12
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
- 623,446
- 136
- 1,297
- 1,155
-
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 Sep 09 '10 at 22:52
-
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 Sep 09 '10 at 22:54
-
@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 Sep 09 '10 at 22:54
-
-
1@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 Sep 09 '10 at 22:55
-
@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 Sep 09 '10 at 22:56
-
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 Sep 09 '10 at 23:00
-
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 – Stephen Way Sep 09 '10 at 23:04
-
@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 Sep 09 '10 at 23:07
-
1