这个线程有点旧,但我也遇到了同样的问题。
正如@quake 所指出的,在同一窗口内的更改不会引发 storageEvent。
要实现所需的“设置拦截”,您必须修补 localSorage 或 sessionStorage 的存储功能。例如:
// somewhere in a Class...
private setStorageItemFunc: (key: string, value: string) => void;
private getStorageItemFunc: (key: string) => string;
private subject$: Subject<string>;
applySettingsInterception() {
// define a Subject
this.subject$ = new Subject();
// just for demonstation purposes. Don't subscribe to the subject, use async pipe instead
this.subject$.subscribe(e => {
console.log('value changed', e);
});
// save original functions
this.setStorageItemFunc = window.localStorage.setItem;
this.getStorageItemFunc = window.localStorage.getItem;
// set storage functions to the newly created interceptor functions
// bind to this to get access to the current object and it's values in interceptor function
window.localStorage.setItem = this.setStorageItem.bind(this);
window.localStorage.getItem = this.getStorageItem.bind(this);
}
private setStorageItem(key: string, value: string): void {
console.log('setStorageItem', key, value);
this.subject$.next(`${key}: ${value}`);
this.setStorageItemFunc.call(localStorage, key, value);
}
private getStorageItem(key: string): string {
const value = this.getStorageItemFunc.call(localStorage, key);
console.log('getStorageItem', key, value);
return value;
}
如您所见,在截获的函数中,您可以调用next()
@damian-c 提到的 Subject 的函数。