How to log out when closing the browser

Here, I want to log out when the browser is closed. For this I did R&D and found that the following code will fire when the browser is closed.

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 force the user to log out. But the problem here is that the page is being redirected for that time and this event is firing.

I want to use this feature so that the user can log out. But this is going wrong. Please help me to make this functionality.

+3


source to share


2 answers


But the problem here is that the page is being redirected for this time and this event is firing.

I am assuming this is a redirect you are doing yourself. If so, why not use a global variable to differentiate your redirects from your client's redirects? Something like that:

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

      



and in your event onbeforeunload

you check if this redirect was done by you or not. If so, then there is no need to call the function logout()

:

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

      

+1


source


Another solution is to use Window.sessionStorage . When the user logs in, you set the sessionStorage variable to "true", when they log out, you set it to "false", and this variable will be removed from sessionStorage when the browser is closed. If you need to share the sessionStorage variable across tabs in the same browser instance, a great example was posted here



0


source







All Articles