onbeforeunload Demo 2

This demo illustrates how to use a JavaScript global variable to supress the dialog box when leaving the page when the Save button is clicked. Try clicking the Save button, you'll note that it doesn't prompt you with a dialog box asking if you're sure you want to leave the page, as it does in the first demo.

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... Note that you can now click the Save button and there's no dialog box displayed. Neat, eh?

What is your name:
What is your age:

Source Code

<script language="JavaScript">
  var needToConfirm = true;
  window.onbeforeunload = confirmExit;
  function confirmExit()
    if (needToConfirm)
      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?";


<input type="Submit" value="Save" onclick="needToConfirm = false;" />

Return to the article...