diff --git a/package.json b/package.json index dffe5e2..271ae99 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storage-proxy", - "version": "1.1.1", + "version": "1.1.2", "description": "Use web storage (localStorage/sessionStorage) just like plain objects using ES6 Proxies.", "author": "Ian K Smith ", "license": "MIT", diff --git a/src/lib.ts b/src/lib.ts index ef44879..69e4322 100644 --- a/src/lib.ts +++ b/src/lib.ts @@ -4,6 +4,12 @@ import onChange from 'on-change'; // --- Types & constants ---------------------------------------------------- // +/** Web storage targets: `localStorage` and `sessionStorage`. */ +export enum StorageTarget { + Local = 'localStorage', + Session = 'sessionStorage', +} + const namespaceSymbol = Symbol('namespaceSymbol'); const isStorageProxy = Symbol('isStorageProxy'); const storageTargetSymbol = Symbol('storageTargetSymbol'); @@ -12,12 +18,6 @@ const storageProxyIntegrityKey = '__storageProxyIntegrity'; const isStorageAvailableCache: Map = new Map(); -/** Web storage targets: `localStorage` and `sessionStorage`. */ -export enum StorageTarget { - Local = 'localStorage', - Session = 'sessionStorage', -} - /** The object type created by `StorageProxy.createLocalStorage()` and `StorageProxy.createSessionStorage()`. */ export type StorageProxyObject = Partial & { readonly [namespaceSymbol]: string; @@ -119,6 +119,17 @@ function createProxy( }, }); + // Sync a `StorageProxyObject` if changes occur to its namespace in another + // window. + window.addEventListener('storage', ev => { + if (StorageProxy.isStorageAvailable(storageTarget)) { + if (ev.key === namespace && ev.storageArea === window[storageTarget]) { + const data = getDataFromStorage(namespace, storageTarget); + for (const [key, value] of Object.entries(data)) storageProxy[key] = value; + } + } + }); + if (defaults) { for (const [key, value] of Object.entries(defaults)) { if (isUndefined(data[key])) { diff --git a/test/src/storage-proxy.spec.ts b/test/src/storage-proxy.spec.ts index 9aebb59..8edff09 100644 --- a/test/src/storage-proxy.spec.ts +++ b/test/src/storage-proxy.spec.ts @@ -200,6 +200,7 @@ export class StorageProxyTestFixture { @Test('Clearing `StorageProxy` removes all keys from both `WebStorage` and the local object') public clearStorageTest() { + localStorage.clear(); StorageProxy.clearStorage(this.lStore); Expect(this.lStore.alreadySetDefault).toBeNull();