2

I'm trying to create window event listener that must listen for the event in the other tab, where opened another instance of the same application.
Some service:

public validateItemAgainstServer = (item: EspApplication) => {
    ...
         window.localStorage.setItem('item', "|")
      ...
    });
  }

Component

constructor(private winRef: WindowRef) {
    winRef.nativeWindow.addEventListener('storage', function (e) {
      console.log("storage event occured");
   }, false);
    window.addEventListener('storage', function (e) {
      console.log("storage event occured");
   }, false);
  }

WinRef

import { Injectable } from '@angular/core';

function _window(): any {
   // return the global native browser window object
   return window;
}

@Injectable()
export class WindowRef {
   get nativeWindow(): any {
      return _window();
   }
}

Regretfully, onstorage event was not fired. Is it possible to fix this solution or may be there is some better ideas of how to synchronize two tabs in Angular?

andrey.shedko
  • 3,128
  • 10
  • 61
  • 121
  • Possible duplicate of [How can I watch for changes to localStorage in Angular2?](https://stackoverflow.com/a/47683091/11065438) – Pushkar Adhikari Feb 25 '19 at 10:25
  • 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) – Pushkar Adhikari Feb 25 '19 at 10:25
  • Could you check (via Browser) if window.localStorage.getItem('item') has any value? – WSD Feb 25 '19 at 11:01
  • @JoshGuzman, what is interesting, event was fired if manually remove value from localStorage via dev tools and yes - there was not value on getItem() – andrey.shedko Feb 25 '19 at 11:05
  • 2
    Well, after applying bind to event listener function it starts to work. – andrey.shedko Feb 25 '19 at 11:15
  • 1
    I would recommend you this article for a better understanding about the subject https://www.bennadel.com/blog/3191-syncing-localstorage-in-memory-cache-with-storage-events-in-angular-2-1-1.htm – WSD Feb 25 '19 at 11:21
  • 1
    You could use arrow functions instead of `bind()`, or even `fromEvent('storage')` from RxJS as well. – Mezo Istvan Feb 25 '19 at 15:50

1 Answers1

0

Check the live example here!

  @HostListener('window:storage')
  onStorageChange() {
    console.log('change...');
  }