broadcast-channel-storage
localStorage-like API to share temporary state across tabs using Broadcast Channel.
npm install broadcast-channel-storage
import { BroadcastChannelStorage } from 'broadcast-channel-storage';
const storage = new BroadcastChannelStorage();
You can also provide optional values to the constructor:
const storage = new BroadcastChannelStorage({
channelName: 'my-channel', // BroadcastChannel name. Default is '__broadcast-channel-storage'
responseTimeoutMs: 200, // Timeout while waiting for response from sync/ready. Default is 200ms
});
storage.setItem('key', 'value');
const value = storage.getItem('key');
storage.removeItem('key');
storage.clear();
Although the getItem
method can be run at any time. You may wish to wait until the initial sync has completed before getting the value:
await storage.ready();
const value = storage.getItem('key');
console.log(value);
You can force a sync using the sync()
method:
await storage.sync();
Changes made to current instance
storage.addEventListener('change', (event) => {
console.log(
`Key ${event.key} changed from ${event.oldValue} to ${event.newValue}`,
);
});
change
events are fired for the current instance (that the listener was added to) when a value is changed on it via setItem
, removeItem
or clear
.
Changes made to other instances, after syncing to current instance
storage.addEventListener('storage', (event) => {
console.log(
`Key ${event.key} changed from ${event.oldValue} to ${event.newValue}`,
);
});
Note: Similar to the original localStorage storage
event, changes made in one BroadcastChannelStorage
instance will emit storage
events for other instances, but not for the instance where the change was made.
length
: Gets the number of values.values
: Returns all the values.isReady
: A flag that is true when the initial sync has happened.isClosed
: A flag that is true when the channel is closed.isLastInstance
: A flag that is true when it is known that this is the finalBroadcastChannelStorage
instance.
To force updating the isLastInstance
property:
await storage.sync();
console.log(storage.isLastInstance);
The library extends EventTarget
and emits the following events:
change
: Emitted on current instance when a storage item is changed.storage
: Emitted on other instances when a storage item is changed.ready
: Emitted when the initial sync has completed.closed
: Emitted when the current storage instance is closed.last-instance
: Emitted when theisLastInstance
flag changes.
The change
and storage
events are similar, a subset of a standard storage
event:
{
key: string | null;
oldValue: string | null;
newValue: string | null;
}
The last-instance
event:
{
isLastInstance: boolean;
}
Sets the value for the specified key.
Gets the value for the specified key.
Removes the specified key.
Clears all keys.
Registers an event listener for the specified event.
Waits until the initial sync has happened.
Forces a sync with other instances.