How to logout my application when I closed the window?

40,202

Solution 1

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).

Solution 2

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.

Solution 3

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

Solution 4

Some websites are using the following script to detect whether window is closed or not.

if(window.screenTop > 10000)
alert("Window is closed");
else
alert("Window stillOpen");

You need to add the correct action instead of alert()

also take a look HERE - I think this is somthing you need to detect the window closing

Solution 5

I got the Solution by,

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

Thanks for all who supported me...

Share:
40,202
Fisher Man
Author by

Fisher Man

I am just a fresher to IT industry . I love to work in java and willing to learn the new technologies in Java....

Updated on November 13, 2021

Comments

  • Fisher Man
    Fisher Man over 2 years

    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...

  • epascarello
    epascarello over 11 years
    BUT it is impossible to call the server and guarantee to make it to the server.
  • AlexStack
    AlexStack over 11 years
    then you can open a small popup window to take care of it or use window.onbeforeunload event handler to warn the user.
  • epascarello
    epascarello over 11 years
    pop up window will be blocked by a pop up blocker, plus it still misses all the edge cases.
  • Fisher Man
    Fisher Man over 11 years
    This helped me and got the solution...Thanks a lot ALEXSTACK.
  • AlexStack
    AlexStack over 11 years
    You are welcome. If you are using the popup window, you can do the logout process in that page behind the scene while warning the user. Then close the window when the logout is done. Maybe this goes so quick that the user will not even see the warning message :)
  • comeGetSome
    comeGetSome almost 9 years
    WATCHOUT: same is executed on page-reload ( F5 ) which you for sure dont want to log your out. For those who dont want to open a popup nor want to use XHR request, there are other possibilities: point either <image/>, <script/> or <iframe/> tag to the logout URL.
  • Giuseppe Garassino
    Giuseppe Garassino over 7 years
    This should be posted as a comment
  • Nayeem
    Nayeem about 6 years
    Did you find any issues sofar with this solution?
  • DrNio
    DrNio almost 6 years
    did you still use onbeforeunload , unload to set the sessionsStorage variable to false ?
  • Maximilian Fixl
    Maximilian Fixl about 5 years
    Good workaround! How do you handle a rememberMe option in that case? Would add the activeSession in the localStorage with a timestamp with the same scope as rememberMe keeps a token valid?
  • CyberAbhay
    CyberAbhay about 5 years
    but how make that value false on browser is closed ?
  • CyberAbhay
    CyberAbhay about 5 years
    I did implemented this solutions it works fine for single tab but if i tried to open app in new tab then there sessionStorage not available and use have to login again.
  • CyberAbhay
    CyberAbhay about 5 years
    I need to logout the user if the tab is closed or refreshed. It should only do force logout on browser is closed.any suggestions
  • jagadeesh puthukkudi
    jagadeesh puthukkudi over 4 years
    This may help on multiple tab open issues [blog.guya.net/2015/06/12/…
  • Ihor Khomiak
    Ihor Khomiak about 3 years
    This solution will logout you also when you refresh the page.
  • Sandip Subedi
    Sandip Subedi about 3 years
    But what if there are multiple tabs open and you don't want to logout when 1 tab is closed?
  • Gaurav Patil
    Gaurav Patil about 2 years
    Best solution, it save my day, Thank you so much