How to stop someone from leaving your page

Tags: jscript, web | Comments (0) | Posted on Thursday 24th of September 2009 05:39:10 PM

You can't.
But you can warn them nicely. Most browsers allows you to send a message to the user. The message reads like this.

Are you sure you want to navigate away from this page?
<You can say something here>
Press OK to continue, or Cancel to stay on the page
Now there's only one proper way of doing this, don't try to do a alert when they are leaving, because they can actually ignore that and leave. The proper way of doing it is
window.onbeforeunload = function () { return "Oh my god, please don't leave."; }
You can also execute things within this function, for example maybe to save the work? This way, while the message pops up, in the background you can save the work through ajax, or maybe even track the user leaving the page.
window.onbeforeunload = function () { save(); return "You have unsaved changes!"; }

Click here to add your own comment!