0

I have to cleared the local storage when browser is closed or the tab in which the site is open is closed but if the website is open in more than one tab than local storage will not be cleared until the last tab is closed.

I have used @HostListener('window:unload', [ '$event' ]) in angular 6. But the problem is that it cannot differentiate between tab closed or window closed. Please help me in finding the solution for this.

export class AppComponent {

  @HostListener('window:unload', [ '$event' ])
  unloadHandler(event) {
    alert('call unload');
  }

  @HostListener('window:beforeunload', [ '$event' ])
  beforeUnloadHander(event) {
    alert('call beforeunload');
  }
}

I want to differentiate between tab closed and browser closed.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • Why not use [sessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) instead? It lives only as long as the browser is open. – zero298 Jul 29 '19 at 18:16
  • [You can't differentiate between tab and browser close](https://stackoverflow.com/q/8134267/215552) – Heretic Monkey Jul 29 '19 at 18:17
  • @zero298 the session storage permist only within the single tab. The use case is that if the user is authorize in one tab and than same site is open in other tab than here the user is authorize as well. – Malik Junaid Awan Jul 29 '19 at 18:31
  • @HereticMonkey do you think is there any other workflow to handle this situation. Thanks – Malik Junaid Awan Jul 29 '19 at 18:32
  • I think your best bet is to use session storage but share it between tabs like here: https://stackoverflow.com/questions/20325763/browser-sessionstorage-share-between-tabs – bryan60 Jul 29 '19 at 19:01
  • I'm not sure why the current behavior is "wrong". Seems like if there exists a tab or window open to your domain, local storage should not be cleared. – Heretic Monkey Jul 29 '19 at 19:51

0 Answers0