how to logout a user when browser closed

断了今生、忘了曾经 提交于 2020-12-26 07:47:18

问题


Here I want to logout an user when they close the browser. For that I have done R&D and found that the following code will fire when we close the browser.

window.onbeforeunload = function() {
  myService.logout();
  return 'Your own message goes here...';
}

Here when I try to close the browser this event will fire and it will make the user to logout. But here the problem is when the page is redirected that time also this event is firing.

I want to use this function to make the user to logout.But it is going wrong.Please help me to do this functionality.


回答1:


But here the problem is when the page is redirected that time also this event is firing.

I guess this is a redirect that you yourself are performing. If that's the case, why don't you use a global variable to differ your redirects with your client's redirects? Something like this:

...
thisismyredirect = true; //before redirecting, set this variable
window.location = "http://www.yoururl.com";
...

and in your onbeforeunload event, you check whether this redirect was performed by you or not. If yes, then no need to call logout() function:

window.onbeforeunload = function() {
    if(!thisismyredirect) {
        myService.logout();
        return 'Your own message goes here...';
    }
}



回答2:


Another solution is to use Window.sessionStorage. When the user logs in, you set the sessionStorage variable to 'true', when they logout you set it to 'false', and the variable will be removed from the sessionStorage when the browser closes. If you need to share the sessionStorage variable across tabs in the same browser instance, a great example has been posted here



来源:https://stackoverflow.com/questions/45255644/how-to-logout-a-user-when-browser-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!