tags:

views:

34

answers:

3

I m making an application in which i want to handle close event of any browser when user clicks on close (X) button of any browser then i want to call my logout servlset then how we handle it.

+1  A: 

You're looking for the onunload:

window.onunload = function() {
  // check the window is closed (see point 1 below)
  // do log out
}

There are 2 problems with this:

  1. It's called whenever the user navigates away from the page, refreshes, or generally unloads as well as when the browser window is closed.
  2. There doesn't seem to be a consistent behaviour between browsers.

I recommend using a different approach.

EMMERICH
+4  A: 

I've searched for a consistent solution to this problem some time ago, and my decision was to handle the situation without believing the browser or the user.

You can't for sure know if a user is leaving your page and when, and even if you use 'onunload', you may not get the event before the browser closes or leaves your page. And browser crashes won't give you any kind of signal, so believing you know the user is still viewing you page and may take any further action is flawed.

The best you can do about logging out an user is put a fitting session timeout, and if you need further control, you may try adding AJAX calls on critical pages with 'I'm alive' signals, and then logging out users that are not responding anymore (that would require AJAX/JS enabled browser and may exclude potential users).

mdrg
+1 - don't rely on browsers.
Nivas
i m agree with your solution, but i want to add this handling to logout automatically when user close browser before logout . in my application if user directly close browser without logout then user cant login before 20 minutes .
Dharmendra Katariya
Keep in mind that no matter what you come up with, no matter how clever, a logout signal is NEVER assured, as I explained above. You may send a logout command using 'onunload', but you'll have to handle it properly so that you don't lot out a user that is navigating to another page of your system, plus it won't work all the time. My honest opinion is that it is not worth the effort. Just live with the lost sessions being killed by timeout.
mdrg
Ok thanks for Your suggestion .
Dharmendra Katariya
+1  A: 

You have to go with session timeout. Since you have tagged your question JSP, I think it is a java web application that you are talking about.

You generally have a session timeout listener, and have your "logout" code in the listener.

Generally don't rely on client side events: a browser/system crash, shutdown without closing the browser etc will not trigger the events.

Nivas
pls can u specify in detail or u can send me example
Dharmendra Katariya