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.
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:
- It's called whenever the user navigates away from the page, refreshes, or generally unloads as well as when the browser window is closed.
- There doesn't seem to be a consistent behaviour between browsers.
I recommend using a different approach.
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).
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.