6

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.

Talha Awan
  • 4,573
  • 4
  • 25
  • 40
Gen
  • 2,400
  • 4
  • 24
  • 46

3 Answers3

2

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...';
    }
}
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
1

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

Vivens Ndatinya
  • 154
  • 1
  • 4
0
tabOrBrowserStillAliveInterval;

constructor() {
  // system should logout if the browser or last opened tab was closed (in 15sec after closing)
  if (this.wasBrowserOrTabClosedAfterSignin()) {
    this.logOut();
  }

  // every 15sec update browserOrTabActiveTimestamp property with new timestamp
  this.setBrowserOrTabActiveTimestamp(new Date());
  this.tabOrBrowserStillAliveInterval = setInterval(() => {
    this.setBrowserOrTabActiveTimestamp(new Date());
  }, 15000);
}

signin() {
  // ...
  this.setBrowserOrTabActiveTimestamp(new Date());
}

setBrowserOrTabActiveTimestamp(timeStamp: Date) {
  localStorage.setItem(
    'browserOrTabActiveSessionTimestamp',
    `${timeStamp.getTime()}`
  );
}

wasBrowserOrTabClosedAfterSignin(): boolean {
  const value = localStorage.getItem('browserOrTabActiveSessionTimestamp');

  const lastTrackedTimeStampWhenAppWasAlive = value
    ? new Date(Number(value))
    : null;
  const currentTimestamp = new Date();
  const differenceInSec = moment(currentTimestamp).diff(
    moment(lastTrackedTimeStampWhenAppWasAlive),
    'seconds'
  );

  // if difference between current timestamp and last tracked timestamp when app was alive
  // is more than 15sec (if user close browser or all opened *your app* tabs more than 15sec ago)
  return !!lastTrackedTimeStampWhenAppWasAlive && differenceInSec > 15;
}

How it works: If the user closes the browser or closes all opened your app tabs then after a 15sec timeout - logout will be triggered.

  • it works with multiple windows open
  • no additional load on the server
  • no problem with F5 / refresh

Browser limitations are the reason why we need 15sec timeout before logout. Since browsers cannot distinguish such cases: browser close, close of a tab, and tab refresh. All these actions are considered by the browser as the same action. So 15sec timeout is like a workaround to catch only the browser close or close of all the opened your app tabs (and skip refresh/F5).

Ihor Khomiak
  • 1,151
  • 11
  • 17
  • It's looks good, but the issue you have here is that you have to open the page again in order to ask for logout. I would add this kind of code in the BE , and check that if the BE didn't get some notification from the UI that the session is lived then it will do logout. – Ofir Hadad Oct 25 '21 at 18:10