Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Back to Basics – OnBeforeUnload Event

5.00/5 (1 vote)
12 Oct 2010CPOL1 min read 17.2K  
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)