最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - clear token when browser is closed in angular 2 - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 6

The 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();
    }
  }
发布评论

评论列表(0)

  1. 暂无评论