Show ‘Are you sure you want to navigate away from this page’ message like Hotmail

If you start typing an email in Hotmail then navigate away without saving or sending it you get the following message:

OnBeforeUnload

This is done by using the onbeforeunload window event.  This event can be used to perform any processing needed before navigating to a new page, but if the event handler returns a string you get this confirmation dialog with your own string replacing “You haven’t sent this message. Are you sure you wan’t to discard it?“.  If you press OK then the navigation continues, and if you press Cancel then you remain on the same page.

Here is an example of how to use the event:

<script language="javascript" type="text/javascript">
    window.onbeforeunload = function() { return "Your message here:"; }
</script>

This could come in useful if you had a form on your page, and you don’t want the user to accidentally navigate away from the page and loose what they have entered.

Posted on by Joe in ASP.NET, JavaScript

2 Responses to Show ‘Are you sure you want to navigate away from this page’ message like Hotmail

  1. Erick

    The same logic also fires when you click on any link that is one the page. What if you only wanted this when the page is closed?

  2. Joe

    Hi Erick

    Not sure you’d be able to do that as the event fires before the window unloads for whatever reason.

    Joe

Add a Comment