JavaBlog.fr / Java.lu DEVELOPMENT,WEB Javascript: Confirm closing/unloading the page with the javascript event onbeforeunload

Javascript: Confirm closing/unloading the page with the javascript event onbeforeunload

In some scenarios, it is good to ask the user for confirmation if he really wants change pages and therefore lose all data entered in a form. This can be handy when the form is time consuming. For this, there is a DOM event beforeunload which occurs just before unloading the page.

addBeforeUnloadHandler();
function addBeforeUnloadHandler() {
	window.onbeforeunload = function(){ return 'Hi, are you sur to quit this page?'; };
}

The return value is the text that is displayed in the confirmation message:

It is very easy to remove this event:

function removeBeforeUnloadHandler() {
	window.onbeforeunload = null;
}

Here is the Microsoft reference concerning this event:

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.

Notes:
– This event is not standardized, however, Firefox and Safari support this feature correctly, while Opera does not seem to support this event.
– With Ajax, in general, the whole page does not refresh, while the content of a DIV is updated. So this solution must be coupled to specific javascript code (global variable).

In the case, where, user clicks on a button which changes the page location property of window object like:

<input type="button" onclick="javascript:goToSiteHandler();" value="http://www.javablog.fr" />
<SCRIPT>

function goToSiteHandler() {
	document.location='http://www.javablog.fr';
}
</SCRIPT>

..then a javascript error appears in IE:

So, a simple solution is to arround the code in handler by “try..catch” instructions:

<input type="button" onclick="javascript:goToSiteHandlerWithTryCatch();" value="http://www.javablog.fr" />

<SCRIPT>
function goToSiteHandlerWithTryCatch() {
	try { // This try is necessary to avoid exception when a "window.onbeforeunload" event handler is present
		document.location='http://www.javablog.fr';
	} catch( e ) { }
}

Download examples: testHUO_onbeforeunload_JS.html

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

Related Post