broadcast-channel

repository·master·Indexed 24 days ago

https://github.com/pubkey/broadcast-channel

A 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.

Tokens
1.9K
Snippets
0
Records
17
Agent score
84%

What's inside broadcast-channel

  1. What is BroadcastChannel

    master
    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.
  2. Send messages with postMessage()

    master

    Use postMessage(msg) to send data over the channel. This method returns a Promise that 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.

  3. Use LeaderElectionWebLock for high-performance leader election

    master

    The LeaderElectionWebLock class 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 broadcastChannel instance and an options object. You can then use awaitLeadership() to wait for the instance to become the leader and hasLeader() to check if a leader currently holds the lock.

  4. Close a BroadcastChannel

    master

    Call close() to shut down the channel. This method is asynchronous and returns a Promise.

    When close() is called, the following lifecycle occurs:

    1. The channel is marked as closed.
    2. It waits for all currently pending postMessage promises to resolve.
    3. It executes any registered 'before-close' hooks (if implemented).
    4. It invokes the underlying method's close logic.

    Once closed, you cannot send further messages through this instance.

  5. LeaderElectionWebLock API Reference

    master

    The LeaderElectionWebLock class provides the following methods for managing leadership via the Web Locks API:

    • hasLeader(): Returns a Promise<boolean> that resolves to true if a lock with the corresponding name is currently held by any tab/process, and false otherwise.
    • awaitLeadership(): Returns a Promise that resolves when the current instance successfully acquires the lock and becomes the leader. If the instance is destroyed via die() while waiting, the promise will not resolve.
    • die(): Terminates the election instance, cleans up listeners, releases internal resources, and sends a 'death' message via the broadcastChannel to notify other participants.
  6. Send internal leader messages with sendLeaderMessage()

    master
    The sendLeaderMessage function is used to broadcast internal coordination messages specifically for leader election. It constructs a message object containing the context: 'leader', the specified action, and the leaderElector.token. The message is then sent via the postInternal method of the leaderElector.broadcastChannel.
  7. Initialize a BroadcastChannel

    master

    Create a new BroadcastChannel instance by providing a name and an optional options object. The channel will automatically select the best available communication method (e.g., native BroadcastChannel, 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 postMessage will wait for this preparation to complete.

  8. Listen for messages using onmessage or addEventListener

    master

    You can listen for incoming messages using two patterns:

    1. The onmessage property: Setting this property will overwrite any previous onmessage listener. It is intended for a single primary listener.
    2. 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.

  9. Manage leader status with beLeader()

    master

    The beLeader function transitions a leaderElector instance into the leader state. It sets the internal leader flags, registers a cleanup function to call leaderElector.die() when the instance is unloaded, and attaches an internal listener to the broadcastChannel to handle leader-related messages.

    When a leader is active, it listens for apply actions from other instances and responds with a tell message. If the instance receives a tell message 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 another tell message to ensure the other leader is aware of the conflict.