Doing some stuff right before the user exits the page

Posted by Mike on Stack Overflow See other posts from Stack Overflow or by Mike
Published on 2010-03-15T08:24:58Z Indexed on 2010/03/15 8:39 UTC
Read the original article Hit count: 231

I have seen some questions here regarding what I want to achieve and have based what I have so far on those answer. But there is a slight misbehavior that is still irritating me.

What I have is sort of a recovery feature. Whenever you are typing text, the client sends a sync request to the server every 45 seconds. It does 2 things. First, it extends the lease the client has on the record (only one person may edit at one time) for another 60 seconds. Second, it sends the text typed so far to the server in case the server crashes, internet connection fails, etc. In that case, the next time the user enters our application, the user is notified that something has gone wrong and that some text was recovered. Think of Microsoft or OpenOffice recovery whenever they crash!

Of course, if the user leaves the page willingly, the user does not need to be notified and as a result, the recovery is deleted. I do that final request via a beforeunload event.

Everything went fine until I was asked to make a final adjustment... The same behavior you have here at stack overflow when you exit the editor... a confirm dialogue.

This works so far, BUT, the confirm dialogue is shown twice. Here is the code.

The event

if (local.sync.autosave_textelement) {
   window.onbeforeunload = exitConfirm;
}

The function

function exitConfirm() {
   var local = Core;
   if (confirm('blub?')) {
      local.sync.autosave_destroy = true;
      sync(false);
      return true;
   } else {
      return false;
   }
};

Some problem irrelevant clarifications:

  • Core is a global Object that contains a lot of variables that are used everywhere.
  • sync makes an ajax request. The values are based on the values that the Core.sync object contains. The parameter determines if the call should be async (default) or sync.

Edit 1

I did try to separate both things (recovery deletion and user confirmation that is) into beforeunload and unload. The problem there was that unload is a bit too late. The user gets informed that there is a recovery even though it is scheduled to be deleted. If you refresh the page 1 second later, the dialogue disappears as the file was deleted by then.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about javascript-events