Redirect to logout link after closing the last tab

811 views Asked by At

As per the requirement, I have to log out the user when he closes the last tab on a browser.

    ngOnInit() {
        let counter: any = this.cookieService.get('screenCounterCookie');
        counter ? ++counter : (counter = '1');
        this.cookieService.set('screenCounterCookie', counter);
    }


    @HostListener('window:beforeunload', ['$event'])
    ngOnDestroy() {
        let counter: any = this.cookieService.get('screenCounterCookie');
        if (counter > 1) {
            --counter;
            this.cookieService.set('screenCounterCookie', counter);
        } else {
            this.cookieService.delete('screenCounterCookie');
            window.open(environment.cognitoLogoutURL);
        }
    }

The behaviour is erratic. Sometimes it reduces the counter, sometimes it doesn't. Also, I have to handle the refresh, multiple tabs close and browser close logic here.

How can I implement it?

3

There are 3 answers

0
Naman Jain On BEST ANSWER

Keeping count of total tabs: https://jsbin.com/mipanuro/1/edit?html,js,output (Refer to this)

Method 1 (Will make a POST call):

Using BeaconAPI (navigator.sendBeacon()). This will happen in the background.

Method 2 (Will work for GET Call as well):

Using fetch and keep-alive

Method 3 (Websocket):

Ping your backend every few minutes or so. And if there's no ping the backend can invalidate your session.

0
Jahrenski On

The only sure way to implement this that I can think of is using websockets and the concept of keep-alive. Or a manual periodic poke to the server to reset a timer that would logout the user if the timer runs out.

You can't trust the browser in a cross-platform way to allow you to fire an event when the browser closes or that the user loses electric power.

2
Raphaël Balet On

I've improved a little bit your logics while not using the ngOnDestroy. I've tried it and seems to work.

import { Component } from '@angular/core'

@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  constructor() {
    const counter = localStorage.getItem('screenCounterCookie') || 0

    localStorage.setItem('screenCounterCookie', (Number(counter) + 1).toString())

    window.addEventListener('beforeunload', () => {
      const counter: number = Number(localStorage.getItem('screenCounterCookie')) - 1
      localStorage.setItem('screenCounterCookie', counter.toString())

      if (counter <= 0) {
        localStorage.removeItem('screenCounterCookie')
        console.log('logout')
        // Your logout
      }
    })
  }
}