Skip to content

Commit

Permalink
broadcastchannel: polyfill close method - closes #61
Browse files Browse the repository at this point in the history
  • Loading branch information
dmonad committed Mar 20, 2023
1 parent be7d1b5 commit dd3f8f4
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
10 changes: 9 additions & 1 deletion broadcastchannel.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

/**
Expand All @@ -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 */

Expand Down
11 changes: 10 additions & 1 deletion storage.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* global localStorage, addEventListener */
/* eslint-env browser */

/**
* Isomorphic variable storage.
Expand Down Expand Up @@ -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))
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
}
},
Expand Down

0 comments on commit dd3f8f4

Please sign in to comment.