I need to warn users about unsaved changes before they leave a page (a pretty common problem).
window.onbeforeunload = handler
This works but it raises a default dialog with an irritating standard message that wraps my own text. I need to either completely replace the standard message, so my text is clear, or (even better) replace the entire dialog with a modal dialog using jQuery.
So far I have failed and I haven't found anyone else who seems to have an answer. Is it even possible?
Javascript in my page:
<script type="text/javascript">
window.onbeforeunload = closeIt;
</script>
The closeIt() function:
function closeIt()
{
if (changes == "true" || files == "true")
{
return "Here you can append a custom message to the default dialog.";
}
}
Using jQuery and jqModal I have tried this kind of thing (using a custom confirm dialog):
$(window).beforeunload(function () {
confirm('new message: ' + this.href + ' !', this.href);
return false;
});
which also doesn't work – I cannot seem to bind to the beforeunload
event.
Best Answer
You can't modify the default dialogue for
onbeforeunload
, so your best bet may be to work with it.Here's a reference to this from Microsoft:
The problem seems to be:
onbeforeunload
is called, it will take the return value of the handler aswindow.event.returnValue
.false
is parsed as a string, the dialogue box will fire, which will then pass an appropriatetrue
/false
.The result is, there doesn't seem to be a way of assigning
false
toonbeforeunload
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 genericbind
syntax.Edit 09/04/2018: custom messages in onbeforeunload dialogs are deprecated since chrome-51 (cf: release note)