gossamer/broadcast_channel

A named channel that broadcasts messages to every other BroadcastChannel of the same name in the same agent — workers on the same origin, same-origin browser tabs and iframes. Construct one with new, send with post_message, and react to incoming messages via set_on_message.

Types

A named broadcast channel shared across same-origin contexts.

See BroadcastChannel on MDN.

pub type BroadcastChannel

Reasons a post_message call can fail.

pub type PostMessageError {
  DataClone
  InvalidState
}

Constructors

  • DataClone

    data can’t be serialized by the structured-clone algorithm — functions, symbols, and most class instances aren’t cloneable.

  • InvalidState

    The channel has been closed.

Values

pub fn close(channel: BroadcastChannel) -> Nil

Closes the channel. Messages posted to other channels of the same name no longer arrive here.

pub fn name(channel: BroadcastChannel) -> String

The name the channel was constructed with.

pub fn new(name: String) -> BroadcastChannel

Creates a BroadcastChannel for the given name. Any other channel of the same name in the same agent will receive messages posted here.

pub fn post_message(
  channel: BroadcastChannel,
  data: a,
) -> Result(Nil, PostMessageError)

Sends data to every other BroadcastChannel of the same name. Returns DataClone if data can’t be serialized by the structured-clone algorithm, or InvalidState if the channel has been closed.

pub fn set_on_message(
  channel: BroadcastChannel,
  handler: fn(dynamic.Dynamic, BroadcastChannel) -> a,
) -> Nil

Registers a handler invoked with each broadcast message’s data payload. The handler also receives the BroadcastChannel so it can reply via post_message from inside. Decode the payload with gleam/dynamic/decode. ArrayBuffer payloads are exposed as BitArray; other values pass through unchanged. Equivalent to JavaScript’s channel.onmessage.

Search Document