1

I want to logout my application when closing last browser tab. I added @HostListener in my app component. Consoling tabcount in constructor gives exact count of opened tab but can't understand why my condition doesn't meet my requirement. Currently it's always logged me out.

app.component.ts

constructor(
    private authService: AuthService
) {
    console.log(tabCount.tabsCount());
}

// Handle session on browser tab close . . .
@HostListener('window:beforeunload', ['$event'])
public beforeunloadHandler($event) {
    console.log(tabCount.tabsCount());
    if (localStorage.getItem('rememberMe') == null){
        if (tabCount.tabsCount() == 1){
            console.log(tabCount.tabsCount());
            this.authService.logout();
        }
    }
}

Logout method:

logout(): void {
    $('.modal').modal('hide');
    localStorage.removeItem('accessToken');
    localStorage.removeItem('session_data');
    this.router.navigate(['/login']);
}
kazinayem2011
  • 348
  • 6
  • 20

1 Answers1

0

Without more information (the tabsCount implementation would be really helpful), I can only advise the following:

  1. Open 3 tabs simultaneously. When you close the third, does it log you out?
  2. This will not work if you refresh the last open tab. This event fires when you close the window but also when you refresh it, so this will most probably create some side effects for your application.

My guess is that you use local storage like here to get the number of tabs, and something goes wrong with the calculation.

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
  • Sometimes closing/refresh second/third tab it log me out. I updated logout method. Can you suggest me any suitable way to meet this requirement? – kazinayem2011 Nov 17 '19 at 09:14
  • Forget about **localStorage.getItem('rememberMe')**. This is just a check of remember me functionality. – kazinayem2011 Nov 17 '19 at 09:25