当浏览器关闭时清除本地存储 [英] Clear local storage when the browser closes in angular

查看:659
本文介绍了当浏览器关闭时清除本地存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个angular 5应用程序.这是使用基于令牌的系统.当前我将令牌存储在本地存储中.我希望在关闭浏览器时清除本地存储.并在浏览器刷新时不清除本地存储.我之所以不使用sesionstorage,是因为在新标签页或窗口中打开页面会导致新会话的启动.我该如何尝试在app.component

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');
}

但是浏览器关闭时不会触发.实现此用例的最佳方法是什么.在使用令牌的情况下,是否使用cookie存储是一种好方法

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

推荐答案

您应该这样做...

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();
    }
}

注意:onBeforeUnload在浏览器关闭事件上执行

Note : onBeforeUnload is executing on browser close event

这篇关于当浏览器关闭时清除本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆