Gags
Gags

Reputation: 3829

Remove session storage when user leaves the app

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.

The OnDestroy does not seem to fire when the application is closed.

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?

Upvotes: 2

Views: 29926

Answers (1)

Haseoh
Haseoh

Reputation: 930

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.

Upvotes: 7

Related Questions