rari
rari

Reputation: 155

How to clear local storage after close the browser?

How to clear local storage after close the browser? Using google, i found only this:

@HostListener("window:onbeforeunload",["$event"])
clearLocalStorage(event){
    localStorage.clear();
}

But it cleans local storage after updating the page, but I don’t need it. I also know that can use sessionStorage instead of localStorage, but this is not suitable, since I do need to save the session not only in one browser tab. How else can I clear the local storage if I close the browser?

ts:

export class AppComponent implements OnInit {

  constructor(private auth: AuthService) { }

  ngOnInit() {
    const potentialToken = localStorage.getItem('auth-token')
    if (potentialToken !== null) {
      this.auth.setToken(potentialToken)
    }
  }
}

Upvotes: 1

Views: 707

Answers (1)

Seba Cherian
Seba Cherian

Reputation: 1793

try this:

window.onbeforeunload = function (e) {
    window.onunload = function () {
            window.localStorage.isMySessionActive = "false";
    }
    return undefined;
};

window.onload = function () {
            window.localStorage.isMySessionActive = "true";
};

Upvotes: 3

Related Questions