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:
<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:
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.