Preventing Accidental Moving Off Site With JavaScript

Wednesday, November 19, 2008 - 17:00

There is nothing more irritating than when you are typing out a long message in a text box and you accidentally move backwards, or clicking on a link and moving off page, therefore losing data you may have entered. There is a solution to stop this happening and it involves the onbeforeunload event.

Although not technically a fully supported event, onbeforeunload is run just before the page is unloaded out of cache. The onunload event occurs right after this, and it is too late by that point.

To prevent a user from moving out of the current page without some form of warning you will need to return some text with the onbeforeunload event. In some browsers that text will be used as part of the message, some browsers will ignore the message but continue anyway.

Include the following body tag in the page you want to incorporate this feature into.

<body onbeforeunload="return 'Warning!';">

This will produce something like the following window.

onbeforeunload event warning

You can also enable this in your code by using the window object in the following way.

<script type="text/javascript">
window.onbeforeunload = runPageUnload;
function runPageUnload(){
 return 'wibble';

You can now include this script in the form itself to prevent users from navigating away from it whilst filling in information. This stops you having to put it on every page, which soon becomes an annoyance.

Note that this doesn't work in Opera, and it doesn't look likely that it will ever work as the Opera team say this is not a bug, despite the fact that every other web browser I can find does it this way.

philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Add new comment