I want to execute the following code when the user closes my application.
我想在用户关闭我的应用程序时执行以下代码。
ngOnDestroy(): void {
sessionStorage.clear();
}
In nutshell, i want to clear sessionStorage of my application once user naviagates away from my app but data shall be preserved when user refreshes the app.
简而言之,一旦用户离开我的应用程序,我想清除应用程序的sessionStorage,但是当用户刷新应用程序时,数据将被保留。
The OnDestroy does not seem to fire when the application is closed.
应用程序关闭时,OnDestroy似乎不会触发。
I have tried below code as well
我也试过下面的代码
ngOnInit() {
window.onbeforeunload = function () {
sessionStorage.clear();
return ''
}
}
I know this is not right place but this clear data on refresh as well :( and moreover this does not work in every browser.
我知道这不是正确的地方,但这个关于刷新的清晰数据:(而且这在每个浏览器中都不起作用。
Where can I place this code to get the behavior I'm looking for, or is there a better way to accomplish what I'm trying to accomplish?
我在哪里可以放置这些代码来获取我正在寻找的行为,或者是否有更好的方法来实现我想要完成的任务?
1 个解决方案
#1
1
You can try this:
你可以试试这个:
import { HostListener } from '@angular/core';
@HostListener('window:unload', ['$event'])
unloadHandler(event) {
window.sessionStorage.clear();
}
Add it in your components (not necessarily inside ngOnInit
). This will clear sessionStorage
whenever you close the browser or tab with your application.
将其添加到组件中(不一定在ngOnInit中)。每当您使用应用程序关闭浏览器或选项卡时,这将清除sessionStorage。
#1
1
You can try this:
你可以试试这个:
import { HostListener } from '@angular/core';
@HostListener('window:unload', ['$event'])
unloadHandler(event) {
window.sessionStorage.clear();
}
Add it in your components (not necessarily inside ngOnInit
). This will clear sessionStorage
whenever you close the browser or tab with your application.
将其添加到组件中(不一定在ngOnInit中)。每当您使用应用程序关闭浏览器或选项卡时,这将清除sessionStorage。