Wayne State University

AIM HIGHER

Web Communications Blog

We build user centered Web sites from the ground up.
Nick West on May 28th, 2008

Javascript on window close event

It’s been pretty busy around here lately so I haven’t had much of a chance to write a blog post. Among other things, I’ve been working with Help Center Live, a live chat web application. The live chat application will hopefully find its way onto the Registrar’s site which is getting a new look and a better feel in the coming months. We needed to modify the application so it would work with our University login both on the user end and the management end. The code was fairly easy to work with and adding the code for the University’s system to authenticate users was a relatively straightforward change.

The problem was in the logout

When logged in we wanted to be sure that the user was actually the same person who originally logged in. This level of authentication guarantees the user already has access to the account with the given accessid. However, since we can’t guarantee that a user will properly log out and we can’t make sessions expire too quickly, we had to figure out a way to log the user out even if they just closed the window.

And so I found the DOM event “beforeunload”

Also known as onbeforeunload and mistakenly thought to be IE only; when attached to the window, the beforeunload event is triggered when the page is unloaded. This, however, includes a link being clicked, a form being submitted, and any other event that will cause the page to go away, including closing the browser window. Without further ado, here’s some code (using some jQuery to make things simple):

First, we bind the startup routine to the load event on window:

$(window).bind('load', function(e){
  close_window = true;
  logged_out = false;
  $("a").bind('click', function(e){
    if(!$(this).hasClass('clickable'))
      close_window = false;
    });
  $("form").bind('submit', function(e){
    close_window = false;
  });
  if (window.addEventListener) {
    window.addEventListener('beforeunload', message, false);
  } else {
    window.attachEvent('onbeforeunload', message);
  }
});

The load routine binds submit and click events to anchor tags and forms so we can ignore those exit cases. Then the beforeunload event is attached to the window in 2 different ways to account for the differences in the big 3 browsers.

Here is the message function triggered by the beforeunload event:

function message(ev) {
  if(close_window){
    if (ev.stopPropagation) {
      ev.stopPropagation();
    } else {
      ev.cancelBubble = true;
    }
    if (ev.preventDefault) {
      logout();
    } else {
      logout();
      ev.returnValue = "Leaving?";
    }
  }
}

And finally the logout function which makes an ajax call to a php script that cleans up any sessions, database info, and cookies:

function logout(){
  if(!logged_out){
    $.ajax({
      type: "GET",
      url: '/chat/inc/logout_connector.php',
      data: "logout=true",
      async: false,
      cache: false,
      success: function(msg){
        console.log("Ajax Repsonse: "+msg);
        logged_out = true;
      }
    });
  }
}

Here’s a quick summary of what is going on, if you need it

When the page is loaded, the close_window variable is set to true. The message method requires the close_window flag to be true, otherwise its routine isn’t run. We’re binding the submit event and click events to forms and anchors respectively then setting close_window to false when those events are triggered. This way the beforeunload event’s code will be skipped when the user leaves the page with those events. When the window is closed, the beforeunload code is run and makes an ajax call to a php script that will clean up the session, cookies, database, etc to assure a clean logout.

This code is currently supported by Firefox 2, IE 6, IE 7, and Safari 3. Opera is the only browser I tested that doesn’t support it.

It’s possible that a jQuery plugin is in the works to do this more easily in the future. If I get the chance to write it, and get it done and working, I’ll make another post about it then.

One Response to “Javascript on window close event”

  1. AlanNo Gravatar Says:

    quite handy info..thanks.!!

Leave a Reply