diff --git a/broadcastchannel.js b/broadcastchannel.js index f99fe32..0959283 100644 --- a/broadcastchannel.js +++ b/broadcastchannel.js @@ -44,7 +44,11 @@ class LocalStoragePolyfill { * @type {null|function({data:ArrayBuffer}):void} */ this.onmessage = null - storage.onChange(e => e.key === room && this.onmessage !== null && this.onmessage({ data: buffer.fromBase64(e.newValue || '') })) + /** + * @param {any} e + */ + this._onChange = e => e.key === room && this.onmessage !== null && this.onmessage({ data: buffer.fromBase64(e.newValue || '') }) + storage.onChange(this._onChange) } /** @@ -53,6 +57,10 @@ class LocalStoragePolyfill { postMessage (buf) { storage.varStorage.setItem(this.room, buffer.toBase64(buffer.createUint8ArrayFromArrayBuffer(buf))) } + + close () { + storage.offChange(this._onChange) + } } /* c8 ignore stop */ diff --git a/storage.js b/storage.js index 42d691a..cea67a3 100644 --- a/storage.js +++ b/storage.js @@ -1,4 +1,4 @@ -/* global localStorage, addEventListener */ +/* eslint-env browser */ /** * Isomorphic variable storage. @@ -61,3 +61,12 @@ export const varStorage = _localStorage */ /* c8 ignore next */ export const onChange = eventHandler => usePolyfill || addEventListener('storage', /** @type {any} */ (eventHandler)) + +/** + * A polyfill for `removeEventListener('storage', event => {..})` that does nothing if the polyfill is being used. + * + * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler + * @function + */ +/* c8 ignore next */ +export const offChange = eventHandler => usePolyfill || removeEventListener('storage', /** @type {any} */ (eventHandler)) diff --git a/tsconfig.json b/tsconfig.json index 579783b..2395b05 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -17,7 +17,7 @@ "paths": { "lib0/*": ["./*"], "lib0/webcrypto": ["./webcrypto.browser.js"], - "lib0/performance": ["./performance.browser.js"], + "lib0/performance": ["./performance.node.js"], "lib0/logging": ["./logging.node.js"] } },