In Angular 2 application we store the token in local storage, now i want to clear the token on browser closing when user not check the remember me option during login. i did it through unload browser event but problem with that event is not fire when user close the browser from task manager in window.
In Angular 2 application we store the token in local storage, now i want to clear the token on browser closing when user not check the remember me option during login. i did it through unload browser event but problem with that event is not fire when user close the browser from task manager in window.
Share Improve this question edited May 19, 2017 at 13:53 bangash asked May 19, 2017 at 12:45 bangashbangash 4181 gold badge5 silver badges12 bronze badges 1- i already implement 'window:beforeunload' but this event is not fire when we close the browser from task manager , – bangash Commented May 19, 2017 at 13:51
3 Answers
Reset to default 6The following should acplish this...
import { Component, HostListener } from "@angular/core";
@Component({
selector: 'app-root',
templateUrl:"./app/app.ponent.html"
})
export class AppComponent {
@HostListener("window:onbeforeunload",["$event"])
clearLocalStorage(event){
localStorage.clear();
}
}
Note : onBeforeUnload
is executing on browser close event
You can use the window.beforeunload event to clear the local storage.
@HostListener('window:beforeunload', ['$event'])
beforeunloadHandler(event) {
localStorage.removeItem(key);
}
Alternatively you can store your information in session storage which is practically the same as local storage except the data gets cleared when the tab is closed.
The below code only remove token on close and not when the page refreshed
@HostListener('window:unload', ['$event'])
async unloadHandler(event) {
if (event.currentTarget.performance.navigation.type !== PerformanceNavigation.TYPE_RELOAD) {
localStorage.clear();
}
}