Preventing Accidental Moving Off Site With JavaScript

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';
}
</script>

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.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
1 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.