PDA

View Full Version : onbeforeunload event parameter and empty return value



Rain Lover
07-30-2014, 07:50 AM
Q1: I have seen the following code in most sources:


window.onbeforeunload = function () {
return 'You might lose your data!';
};

For example:


beforeunload | onbeforeunload event (Internet Explorer) (http://msdn.microsoft.com/en-us/library/ie/ms536907(v=vs.85).aspx)
onbeforeunload event | beforeunload event JavaScript (http://help.dottoro.com/ljhtbtum.php)
javascript - How can I override the OnBeforeUnload dialog and replace it with my own? - Stack Overflow (http://stackoverflow.com/a/276739/478018)


But on MDN (https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload#Example) the function has an extra parameter: (e). Why is that, what is the difference, and which is right?


Q2: It seems that any browser has a default confirmation message that you cannot customize. Chrome, for example, displays:


Are you sure you want to leave this page?

Can I content myself to this message and leave the return value empty:


return '';

Deadweight
07-31-2014, 03:28 AM
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:

When onbeforeunload is called, it will take the return value of the handler as window.event.returnValue.
It will then parse the return value as a string (unless it is null).
Since 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:

Setting the event in jQuery may be problematic, as that allows other 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() {} );