How to logout my application when I closed the window? How to logout my application when I closed the window? ajax ajax

How to logout my application when I closed the window?


There is no exact way to do this with the clientside. There is no event that is fired when the page is exited. It should be done with the Session End event on the server.

You can try to use onbeforeunload or unload, but race conditions will prevent that from happening. AND they do not fire for browsers crashing, lost internet connection, etc.


I dealt with this issue recently in my angularJS app - The main issue was that I don't want to log you out if you refresh, but I do want to if you close the tab.. Ajax requests with onbeforeunload/onunload aren't guaranteed to wait for response, so here is my solution:

I set a sessionStorage cookie on login that is just a bool - set to true when I get login response

sessionStorage.setItem('activeSession', 'true');

Obviously, on logout, we set this flag to false

Either when controller initializes or using window.onload (in my app.js file) - I check for this activeSession bool.. if it is false, I have this small if statement - where if conditions are met I call my logout method ONLOAD instead of onunload

   var activeSession = sessionStorage.activeSession;    if (sessionStorage.loggedOutOnAuth) {        console.log('Logged out due to expiry already')    }    else if (!activeSession) {        sessionStorage.loggedOutOnAuth = true;        _logout()    }

Basically, the "loggedOutAuth" bool let's me know that I just expired you on page load due to the absence of an activeSession in sessionStorage so you don't get stuck in a loop

This was a great solution for me since I didn't want to implement a heartbeat/websocket


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.

window.open("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).