How to logout my application when I closed the window?

后端 未结 9 1925
猫巷女王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 14:07

    I was with this problem here and I come with a different solution:

        checkSessionTime();
        $interval(checkSessionTime, 2000);
        function checkSessionTime() {
            var now = (new Date()).getTime();
            if (!$localStorage.lastPing) {
                $localStorage.lastPing = now;
            }
    
            if ($localStorage.lastPing < now - 5000) {
                $localStorage.lastPing = undefined;
                AuthService.logout();
            } else {
                $localStorage.lastPing = now;
            }
        }
    

    I like this solution cause it doesnt add overhead pinging the server nor rely on the window unload event. This code was put inside the $app.run.

    I am using angular with a JWT auth, this way to me to log out just mean to get rid of the auth token. However, if you need to finish up the session server-side you can just build the Auth service to do one ping when finishing the session instead of keep pinging to maitain session alive.

    This solutionsolves my case cause my intetion is just to prevent unwanted users to access someones account when they closed the tab and went away from the PC.

提交回复
热议问题