[Fixed] Redirect to logout link after closing the last tab


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) {
            this.cookieService.set('screenCounterCookie', counter);
        } else {

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?


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.

Leave a Reply

(*) Required, Your email will not be published