7

I have created an angular 5 application. Which is using a token based system.Currently I am storing the token in the localstorage.I want the localstorage to be clear when the browser closes. and not clear the localstorage when the browser refreshes.The reason that I didn't use sesionstorage is because opening a page in a new tab or window will cause a new session to be initiate. How can I done this I tried with this code in app.component

@HostListener('window:beforeunload', ['$event'])
  beforeunloadHandler(event) {
  alert("KKk")
  localStorage.removeItem('authToken');
}

But it is not firing when the browser closes.What is the best method to achieve this use case. Whether using cookie storage is a good method in case of tokens

Senchu Thomas
  • 518
  • 3
  • 9
  • 24
  • Wanted to point to another SO answer.. [here...](https://stackoverflow.com/a/47203709/6916098) it worked for me. – blogs4t Apr 02 '18 at 13:32

5 Answers5

10

You should do that way...

import { Component, HostListener } from "@angular/core";

@Component({
    selector: 'app-root',
    templateUrl:"./app/app.component.html"
})

export class AppComponent {
    @HostListener("window:onbeforeunload",["$event"])
    clearLocalStorage(event){
        localStorage.clear();
    }
}

Note : onBeforeUnload is executing on browser close event

Umar Tariq
  • 1,191
  • 1
  • 13
  • 14
  • 6
    A correction: it should be "window:beforeunload" i believe and not "window:onbeforeunload". The former worked for me and the latter did not. – blogs4t Apr 02 '18 at 13:40
  • 2
    but it is working when refreshing the page. i do not need. when refreshing the page. can you please help me? – Kumaresan Perumal Jul 27 '18 at 12:20
  • Thanks! I ran into this exact same issue, and your answer was helpful. – JAY PATEL Dec 20 '19 at 07:34
  • @KumaresanPerumal did you find any way to fix the issue even on page reload? – Kannan T Mar 19 '20 at 06:34
  • When attaching functions to window events, I think you'll need to omit the `on` part, so it should be `@HostListener("window:beforeunload",["$event"])` Also, to prevent clearing the localStorage when refreshing the last single tab, I think it should be `@HostListener("window:unload",["$event"])` – Achilles Jul 03 '23 at 13:05
2

We can achieve this through the below approach.

Before Login call this function.

Here we check whether Is there any active tab present. If not cleat the localStorage and if required redirect to login(I have not done redirecting here).

checkActiveTabs() {
        let localStorageTabs: TabModel[] = [];
        const sessionTabId: number = Number(sessionStorage.getItem(AppUtils.TAB_ID));
        localStorageTabs = JSON.parse(localStorage.getItem(AppUtils.TABS));
        if(sessionTabId == 0 && localStorageTabs != null){
            let activeTabs = localStorageTabs.find(item => item.status == 1);
            if(activeTabs == undefined){
                localStorage.clear();
            }
        }
    }

To keep track of the tabs, once logged in invoke the below method.

 setBrowserTabId() {
        let localStorageTabs: TabModel[] = [];
        const sessionTabId: number = Number(sessionStorage.getItem(AppUtils.TAB_ID));
        localStorageTabs = JSON.parse(localStorage.getItem(AppUtils.TABS));
        if (sessionTabId != 0) { // existing active tabs ?
            if (localStorageTabs != null || localStorageTabs != undefined) {
               localStorageTabs.find(item => item.tabId == sessionTabId).status = 1; //tab is refreshed, setting back to active.
            } 
        } else { //new tab
            const tabId = new Date().getTime(); //tab Id
            sessionStorage.setItem(AppUtils.TAB_ID, JSON.stringify(tabId));
            let tabmodel: TabModel = new TabModel();
            tabmodel.tabId = tabId;
            tabmodel.status = 1; //tab is active
            if (localStorageTabs == null) {
                localStorageTabs = [];
            }
            localStorageTabs.push(tabmodel);
        }
         localStorage.setItem(AppUtils.TABS, JSON.stringify(localStorageTabs));
    }

To set inactive tab, invoke this on @HostListener

 @HostListener('window:beforeunload ', ['$event'])
    unloadHandler(event) {
       const sessionTabId = sessionStorage.getItem(AppUtils.TAB_ID);
       const localTabId : TabModel[] = JSON.parse(localStorage.getItem(AppUtils.TABS));
       localTabId.find(item => item.tabId == +sessionTabId).status = 0;
       localStorage.setItem(AppUtils.TABS, JSON.stringify(localTabId));
    }

Note: This logic will not work if browser crashed or if browser closed through windows task manager.

user630209
  • 1,123
  • 4
  • 42
  • 93
1

You could use sessionStorage instead of localStorage.

The main difference between them is that localStorage persists data even after the browser is closed, while sessionStorage only persists data for the current session. When the browser tab is closed, the data stored in sessionStorage is automatically deleted.

0

Try with onDestroy, this gets executed when a directive, pipe or service is destroyed.

ngOnDestroy() { 
      alert("KKk")
      localStorage.removeItem('authToken');
 }
jonhid
  • 2,075
  • 1
  • 11
  • 18
0

You should do it that way.

Add in AppComponent

export class AppComponent implements OnInit{


 constructor() {   
    window.onbeforeunload = function() {
      localStorage.clear();
      return '';
    };
  }
}
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 07 '22 at 16:21
  • put it in ngOnInit – danday74 Aug 29 '23 at 07:53