Fisher Man Fisher Man - 1 year ago 82
Javascript Question

How to logout my application when I closed the window?

In my chat application i am having the logout button and it works fine.

Now I need to logout the application when I closed the browser window also..How can I achieve this...

Thanks in advance...

Answer Source

Add your logout code to the on onunload event.

window.onunload = function () {
    //logout code here...

In JQuery you can use the .unload() function. Remember that you don't have much time so you may send the Ajax request but the result may not reach the client.

Another trick is to open a small new window and handle the logout there."logout url","log out","height=10,width=10,location=no,menubar=no,status=no,titlebar=no,toolbar=no",true);

If you want to disable closing the window (or at least warn the user), you can use this code:

window.onbeforeunload = function(event) {
    //if you return anything but null, it will warn the user.
    //optionally you can return a string which most browsers show to the user as the warning message.
    return true;

Another trick is to keep pinging the client every few seconds. If no reply comes back, assume the user has closed the window, browser has crashed or there is a network issue that ended the chat session anyway. On the client side, if you don't receive this ping package, you can assume that network connection or server has a problem and you can show the logout warning (and optionally let the user login again).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download