Implementing "this page is asking you to confirm that you want to leave"

Well, you need to try to add some other things like form. But something simple is:

EDIT: Fixed HTML;

<html>
<head>

<script language="javascript">
function mymessage()
{
alert("This message was triggered from the onunload event");
}
</script>
</head>

<body onbeforeunload="mymessage()">

<p>close this window and watch the warning box come up!</p>
</body>

</html>

You basically implement a handler for beforeunload event. This allows you to warn your users that they have unsaved data.

Pseudo Code:

  window.onbeforeunload = function warnUsers()
  {
    if (needToConfirm)
    {
      // check to see if any changes to the data entry fields have been made
      if(changesPresent) {
            return message to display
      }
      else {
      // no changes - return nothing      
      }
    }
  }

Here's a very good article that discusses this in depth: http://www.4guysfromrolla.com/webtech/100604-1.shtml Note: This link no longer exists. Here is a copy of it from the Wayback Machine: https://web.archive.org/web/20211020134123/http://www.4guysfromrolla.com/webtech/100604-1.shtml

Note: There is onunload event also but that fires after the page has unloaded, hence is too late to take any reliable action. You should never put any critical code in onunload as that is never guranteed to execute.

Tags:

Javascript