broadcast-channel
repository·master·Indexed 24 days ago
https://github.com/pubkey/broadcast-channelA cross-context messaging API that enables data communication between browser tabs, WebWorkers, Node.js processes, Deno instances, and iframes. Version 7.3.0 includes a unified API for sending and receiving messages via postMessage, as well as built-in leader election mechanisms, including a high-performance implementation using the Web Locks API via the LeaderElectionWebLock class.
What's inside broadcast-channel
- BroadcastChannel is a library that enables data communication between different browser tabs, WebWorkers, Node.js processes, and Deno instances. It provides a unified API for cross-context messaging and includes built-in Leader Election capabilities to coordinate tasks across multiple instances.
Enforce global options for all BroadcastChannels
masterTheenforceOptions(options)function allows you to set a global configuration that will be applied to everyBroadcastChannelinstance created after the call, regardless of the options passed to their individual constructors.LeaderElectionWebLock properties
masterThe following properties are available on a
LeaderElectionWebLockinstance:isLeader: A boolean indicating if the current instance is the active leader.isDead: A boolean indicating if thedie()method has been called on this instance.token: A uniquerandomTokengenerated for this instance.
Send messages with postMessage()
masterUse
postMessage(msg)to send data over the channel. This method returns aPromisethat resolves when the message sending process is complete.If you attempt to call
postMessage()after the channel has been closed, it will throw an error containing a stringified version of the message to assist in debugging.Use LeaderElectionWebLock for high-performance leader election
masterThe
LeaderElectionWebLockclass provides a high-performance leader election mechanism by leveraging the browser's native Web Locks API. It is designed to be faster than standard message-based election methods.To use it, instantiate it with an existing
broadcastChannelinstance and anoptionsobject. You can then useawaitLeadership()to wait for the instance to become the leader andhasLeader()to check if a leader currently holds the lock.Close a BroadcastChannel
masterCall
close()to shut down the channel. This method is asynchronous and returns aPromise.When
close()is called, the following lifecycle occurs:- The channel is marked as
closed. - It waits for all currently pending
postMessagepromises to resolve. - It executes any registered 'before-close' hooks (if implemented).
- It invokes the underlying method's close logic.
Once closed, you cannot send further messages through this instance.
- The channel is marked as
Import BroadcastChannel in non-module environments
masterWhen using the non-module build (ES5) viarequire, you can access the main exports directly on the required object. This build is designed to avoid the need for accessing a.defaultproperty, allowing for standard CommonJS usage.LeaderElectionWebLock API Reference
masterThe
LeaderElectionWebLockclass provides the following methods for managing leadership via the Web Locks API:hasLeader(): Returns aPromise<boolean>that resolves totrueif a lock with the corresponding name is currently held by any tab/process, andfalseotherwise.awaitLeadership(): Returns aPromisethat resolves when the current instance successfully acquires the lock and becomes the leader. If the instance is destroyed viadie()while waiting, the promise will not resolve.die(): Terminates the election instance, cleans up listeners, releases internal resources, and sends a'death'message via thebroadcastChannelto notify other participants.
Send internal leader messages with sendLeaderMessage()
masterThesendLeaderMessagefunction is used to broadcast internal coordination messages specifically for leader election. It constructs a message object containing thecontext: 'leader', the specifiedaction, and theleaderElector.token. The message is then sent via thepostInternalmethod of theleaderElector.broadcastChannel.Initialize a BroadcastChannel
masterCreate a new
BroadcastChannelinstance by providing anameand an optionaloptionsobject. The channel will automatically select the best available communication method (e.g., nativeBroadcastChannel,SharedWorker, or Node.js-specific methods) based on the provided options and the environment.Note that the channel initialization might be asynchronous. The underlying method is prepared during construction, and messages sent via
postMessagewill wait for this preparation to complete.Listen for messages using onmessage or addEventListener
masterYou can listen for incoming messages using two patterns:
- The
onmessageproperty: Setting this property will overwrite any previousonmessagelistener. It is intended for a single primary listener. addEventListener(type, fn): Allows registering multiple listeners for specific event types. For standard messages, use the'message'type.
When a message is received, the listener function is called with the message data.
- The
Manage leader status with beLeader()
masterThe
beLeaderfunction transitions aleaderElectorinstance into the leader state. It sets the internal leader flags, registers a cleanup function to callleaderElector.die()when the instance is unloaded, and attaches an internal listener to thebroadcastChannelto handle leader-related messages.When a leader is active, it listens for
applyactions from other instances and responds with atellmessage. If the instance receives atellmessage while it already believes it is the leader (indicating a potential split-brain scenario where two instances think they are leaders), it triggers the_dpL()callback to notify the application and sends anothertellmessage to ensure the other leader is aware of the conflict.