I need to warn users about unsaved changes before they leave a page (a pretty common problem).
window.onbeforeunload=handler
This works bu
You can't modify the default dialogue for onbeforeunload
, so your best bet may be to work with it.
window.onbeforeunload = function() {
return 'You have unsaved changes!';
}
Here's a reference to this from Microsoft:
When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option to stay on the current page and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.
The problem seems to be:
onbeforeunload
is called, it will take the return value of the handler as window.event.returnValue
.false
is parsed as a string, the dialogue box will fire, which will then pass an appropriate true
/false
.The result is, there doesn't seem to be a way of assigning false
to onbeforeunload
to prevent it from the default dialogue.
Additional notes on jQuery:
onbeforeunload
events to occur as well. If you wish only for your unload event to occur I'd stick to plain ol' JavaScript for it.jQuery doesn't have a shortcut for onbeforeunload
so you'd have to use the generic bind
syntax.
$(window).bind('beforeunload', function() {} );
Edit 09/04/2018: custom messages in onbeforeunload dialogs are deprecated since chrome-51 (cf: release note)