3

I wanted to logout automatically from all the open tabs when logged out in one open tab.

I'm setting a jwt token to localStorage on login and removing the token when logout.

How do I use storage events to logout from all open tabs?

yer
  • 1,454
  • 2
  • 16
  • 33
  • 1
    Possible duplicate of [How can I watch for changes to localStorage in Angular2?](https://stackoverflow.com/questions/35397198/how-can-i-watch-for-changes-to-localstorage-in-angular2) – David Apr 13 '18 at 15:41

1 Answers1

10

You can add event listener on storage as:

window.addEventListener('storage', (event) => {
  if (event.storageArea == localStorage) {
    let token = localStorage.getItem('jwt_token');
    if(token == undefined) { // you can update this as per your key
        // DO LOGOUT FROM THIS TAB AS WELL
        this.router.navigate(['/']); // If you are using router
        // OR
        window.location.href = '<home page URL>';
    }
  }
}, false);
Anshuman Jaiswal
  • 5,352
  • 1
  • 29
  • 46
  • 1
    I can see the alert in other tab, How do I logout user? `(event) => { if (localStorage.getItem('jwt_token') == null) { alert('yes'); } }` – yer Apr 13 '18 at 16:10
  • @RNKushwaha you can write above code in app.component within `ngOnInit` method. – Anshuman Jaiswal Sep 11 '19 at 01:48