The onbeforeunload window event

The onbeforeunload event is a window event that is triggered when the window is about to close the current page. This occurs in a number of situations, including:

  • when you use the forward or back browser buttons
  • when the page is refreshed
  • when the page is closed
  • when you click on a link to a different page

Sometimes you will want to advise a user that they are about to lose some information that they have entered on the current page.

You can use the onbeforeunload to warn people that they may be able to lose some information

window.onbeforeunload = function () {
    return 'If you leave this page you will lose the information that you have entered.';
}

Note that this event differs in how it handles the return value from other JavaScript events. Most events cancel themself if you return false from them. The onbeforeunload event is different, in that whatever is returned (even false) is shown in the warning message.

While it is not possible for scripting to cancel the onbeforeunload event, the user will be able to choose to do so from the warning message that is shown.

Further details on using the onbeforeunload event can be found at: http://www.4guysfromrolla.com/webtech/100604-1.shtml

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: