How to logout my application when I closed the window?

后端 未结 9 1917
猫巷女王i
猫巷女王i 2020-12-15 13:33

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

9条回答
  •  既然无缘
    2020-12-15 13:57

    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

提交回复
热议问题