Click here to Skip to main content
15,887,683 members
Articles / Programming Languages / Javascript
Tip/Trick

Back to Basics – OnBeforeUnload Event

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
12 Oct 2010CPOL1 min read 17K   1  
Back to Basics – OnBeforeUnload Event

There are times when you need to warn your users about unsaved changes before they leave the web page that they are working on. In these times, the simple solution is to use the OnBeforeUnload JavaScript event. In this post, I will explain what is this event and how to use it.

OnBeforeUnload Event

The OnBeforeUnload event is fired prior to a page being unloaded. This is the last place that you can prevent the loss of unsaved data before leaving the page. In order to use the event, you can wire a handler (JavaScript function) and use it to do things and also warn your user from the loss of data. If a string is being assigned as the return value of the handler, a dialog will appear and will give the users the option to stay on the current page and retain that string. The dialog’s text can’t be changed but the return string will be added to it. Here is a simple example of how to use the event:

HTML
<script type="text/javascript">
    window.onbeforeunload = function () {
        return 'You have unsaved data! do you really want to exit?'; 
    }
</script>

and the result when you will close the web page will be:

OnBeforeUnload Fired

Summary

The OnBeforeUnload JavaScript event can be used in order to prevent the loss of valuable data when users exit a web page. It can also annoy your users since whenever they will try to leave the page, they will get the dialog box. So my advice – use this solution only when it is required.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead sparXys
Israel Israel
Gil Fink is a web development expert and ASP.Net/IIS Microsoft MVP. He is the founder and owner of sparXys. He is currently consulting for various enterprises and companies, where he helps to develop Web and RIA-based solutions. He conducts lectures and workshops for individuals and enterprises who want to specialize in infrastructure and web development. He is also co-author of several Microsoft Official Courses (MOCs) and training kits, co-author of "Pro Single Page Application Development" book (Apress) and the founder of Front-End.IL Meetup. You can read his publications at his website: http://www.gilfink.net

Comments and Discussions

 
-- There are no messages in this forum --