From c1e18517918e0ccb2d0a3d7451d58478c8bc65a5 Mon Sep 17 00:00:00 2001 From: Ian K Smith Date: Thu, 19 Dec 2019 17:25:01 -0800 Subject: [PATCH 1/2] Sync StorageProxyObjects between windows --- src/lib.ts | 23 +++++++++++++++++------ test/src/storage-proxy.spec.ts | 1 + 2 files changed, 18 insertions(+), 6 deletions(-) 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(); From 141a0fa93fed9fd8339699c893d46cfe4b513903 Mon Sep 17 00:00:00 2001 From: Ian K Smith Date: Thu, 19 Dec 2019 17:25:15 -0800 Subject: [PATCH 2/2] v1.1.2 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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",