How can you logout a user (invalidate his Session) when a user directly closes his browser window?

Alex Chaffee

Short answer: you can't. Fortunately, sessions expire automatically after a period of time; check your servlet engine documentation to see how to set this timeout period.

I felt that there should be a way to do it from JavaScript; unfortunately, JavaScript doesn't seem to have an onWindowClose handler. JavaScript expert Daniel Zen of Zen Digital writes:

There is no onClose handler, it is the onUnload handler that you want. The problem is you want a page to be 'loaded' when the window is closing. In order to load a page you have to have a window.... So you would have to somehow abort the close (I don't know if this is possible), or open a new window with your URL, and rely on that document to close it's own window (which I have seen pop up a dialog box warning on occasion...)

<BODY onUnload="javascript code">

which won't work if javascript is disabled.

Also, the onUnload handler only works in IE.

If anyone figures out a way to make this work, please let us know.

P.S. Thanks to the many people who submitted answers!

About | Sitemap | Contact