Browser close - how do I know
Wed, 09/29/2010 - 01:15
I've been working some on the security end of a new application and I have a question. Is it possible to know, when the user closes the browser? I would like to do some clean up, when the user simply closes their browser, without actually signing out.
I think javascript has an "onunload" event, but I don't know how to implement it in QCubed.

window.onbeforeunload could be your friend:
try it out:
(warning: closing the window in konqueror does not call onbeforeunload but in firefox it works)
http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm
just put the script on this site at the end of your QForm template file (for example)
Excellent! Thank you Mike, it does exactly what I wanted.
I would not rely on that event at all. It might not fire in some browsers. Users computer might crash. Don't depend on it - build your logic differently.
If you describe what you're trying to accomplish, we can try to help you redesign your logic a bit.
Alex, thanks for the reply.
Actually, my requirement is fairly simple. Right now, I have a "logout" button. When the user presses that button, it makes an Ajax call to a method that does some clean up on the database, to keep track of that user. However, there is always the possibility the user would simply close the tab or close the browser entirely. I would like to have an even fire that will cause the same Ajax call to be made to my "logout" method.
Any other ideas would surely be appreciated!
The only way to do that reliably, IMO, is to use cronjobs to do routine cleanup. Your authentication system should be using sessions in some way, so you will need a separate job that goes through the sessions and kills them/cleans up after them.
Cliff, thanks very much for those ideas. I already have planned cron jobs for cleaning up the mess, so to speak. However, I'm looking for a way to keep track of login/logout times for users. The application is an industrial management system, so it would be more than nice to know who's doing what and for how long. My clients want to also know who was using the system and when. Of course, there will certainly be some situations, where it will be unreliable, like network outages/failures, etc. That's pretty much what the cron jobs will clean up after. So far, it sounds like Mike's idea may be about as good as it gets.
Here's my recommendation: if you want an audit trail, just record every page load. The last page load for a session will be the "logout time". This will be much more reliable.
Alex, there's one other very significant reason I need to know, when a user closes the browser tab. It's not really necessary to know if they closed the browser, but if they only close the tab, it may be very important. Please see this thread.