1

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)
    }
  }
}
rari
  • 155
  • 1
  • 9

1 Answers1

3

try this:

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

window.onload = function () {
            window.localStorage.isMySessionActive = "true";
};
Seba Cherian
  • 1,755
  • 6
  • 18
  • 1
    Wow, if `getItem` and `clear` are set instead of `isMySessionActive`, this will work) – rari Aug 02 '19 at 11:29