onbeforeunload Demo

This demo illustrates how to create an event handler for the client-side onbeforeuload event. Notice that the string returned by the event handler is displayed in the dialog box the user is shown when the page is being unloaded. If the user clicks Cancel, they'll remain on the page; if they click OK, they'll exit the page as they specified (either jumping to another Web page or closing the browser).

Here are some links you can click to leave this page. Note that if you are visiting with Internet Explorer or FireFox 0.9 or higher, you'll be asked if you really want to leave this page. This also works when closing the browser.

Here is a form to simulate a data entry page... One "issue" you'll note here is that when the submit button is clicked it prompts the user, asking if they're sure they want to leave the page. We'll see how to fix this in the article...

What is your name:
What is your age:

Source Code

<script language="JavaScript">
  window.onbeforeunload = confirmExit;
  function confirmExit()
    return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";

Return to the article...