Catching the localStorage change event by key

Hello. (I searched Google, but found nothing useful). I am interested in this question: is it possible to somehow catch changes in localStorage by a specific key in the current tab. I found that you can only report changes to neighboring domain tabs, but this does not suit me. And the purpose of the question: it is necessary to pull out information from the key when changing the storage and write it to the database.

I tried to do something like this, but no result when changing the storage I didn't see it. I added the script to head.

window.addEventListener('storage', function(e) {  
  console.log(e.key);
});
Author: Yumie, 2017-04-14

3 answers

I think this is a terrible solution, but it works, maybe it will push you to a better one.

Unfortunately, I haven't thought of anything better yet.

Https://jsfiddle.net/fe0fjemu/

   setTimeout(() => localStorage.setItem('test', JSON.stringify('отвратитльный пример')), 1000);
setTimeout(() => localStorage.setItem('test', JSON.stringify('плохой код')), 5000);
setTimeout(() => localStorage.setItem('test', JSON.stringify('плохой код')), 8000);
let complexObject = {
    foo: [1, 2, 4, [12, 45], {bar: 1}],
  baz: {
    bon: {
        test: 'qwerty'
    }
  }
};
let complexObject2 = {
    foo: [1, 2, 4, [12, 45], {bar: 1}],
  baz: {
    bon: {
        test: 'qwert'
    }
  }
};
setTimeout(() => localStorage.setItem('test', JSON.stringify(complexObject)), 15000);
setTimeout(() => localStorage.setItem('test', JSON.stringify(complexObject2)), 18000);

let storeValue = '';
const storageListner = setInterval(() => {
    let newValue = localStorage.getItem('test');
    if (localStorage.getItem('test') && storeValue !== newValue) {
        storeValue = newValue;
        console.log(storeValue);
    }
}, 1000);
 0
Author: Антон Ратников, 2017-04-15 00:13:22

For the Angular, I found such a way out,you can also stick it anywhere using the RxJS library:

export class LocalStorageService {
  private productsInCart: Array<any> = JSON.parse(localStorage.getItem('productsInCart')) || {};
  public order$ = new BehaviorSubject(this.productsInCart);
  //пример функции,после которой мне нужно пропихнуть новое значение 
    unsetLSS(id: string){
    delete this.productsInCart[id];
    localStorage.setItem('productsInCart', JSON.stringify(this.productsInCart));
     
     //именно эта строка делает событие
    this.order$.next(this.productsInCart);
    
  }
  
  }
  
   //в той компоненте которая мне нужна
   
   order$ = this.LSS.order$;
   cartProducts: Product[] = [] ; //переменная куда я вставляю значение,этот массив я вывожу потом
   
    constructor(
    private LSS: LocalStorageService
  ){}
      ngOnInit() {
     
      this.order$.subscribe((value) => {
        this.cartProducts = value;
      });
 0
Author: Feria, 2020-05-28 17:48:18

Use

window.addEventListener('storage', function(e) { }

From https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API

 -2
Author: Vladimir P, 2019-11-30 21:13:09