Preventing Accidental Moving Off Site With JavaScript

19th November 2008

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.

 

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.

  1. <script type="text/javascript">
  2. <!--//--><![CDATA[// ><!--
  3.  
  4. window.onbeforeunload = runPageUnload;
  5. function runPageUnload(){
  6. return 'wibble';
  7. }
  8.  
  9. //--><!]]>
  10. </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.