Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear local storage when the browser closes in angular

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

like image 673
Senchu Thomas Avatar asked Feb 27 '18 18:02

Senchu Thomas


People also ask

How do I clear localStorage after closing browser?

You can make use of the beforeunload event in JavaScript.window. onbeforeunload = function() { localStorage. removeItem(key); return ''; }; That will delete the key before the browser window/tab is closed and prompts you to confirm the close window/tab action.

Does local storage persist when browser is closed?

localStorage is a property that allows JavaScript sites and apps to save key-value pairs in a web browser with no expiration date. This means the data stored in the browser will persist even after the browser window is closed.

Which data is cleared when the browser is closed?

localStorage is similar to sessionStorage , except that while localStorage data has no expiration time, sessionStorage data gets cleared when the page session ends — that is, when the page is closed.

Does localStorage clear on shutdown?

Does localStorage clear on shutdown? No, until the user removes it on all browsers. It is persistent meaning the stored data will still be there when you close and re-open the browser window.


2 Answers

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

like image 136
Umar Tariq Avatar answered Sep 22 '22 17:09

Umar Tariq


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.

like image 43
user630209 Avatar answered Sep 23 '22 17:09

user630209