Leptos-Use Guide

use_broadcast_channel

Reactive BroadcastChannel API.

Closes a broadcast channel automatically when the component is cleaned up.

Demo

Usage

The BroadcastChannel interface represents a named channel that any browsing context of a given origin can subscribe to. It allows communication between different documents (in different windows, tabs, frames, or iframes) of the same origin.

Messages are broadcasted via a message event fired at all BroadcastChannel objects listening to the channel.

use leptos::prelude::*;
use leptos_use::{use_broadcast_channel, UseBroadcastChannelReturn};
use codee::string::FromToStringCodec;

#[component]
fn Demo() -> impl IntoView {
let UseBroadcastChannelReturn {
    is_supported,
    message,
    post,
    error,
    close,
    ..
} = use_broadcast_channel::<bool, FromToStringCodec>("some-channel-name");

post(&true);

close();

view! { }
}

Values are (en)decoded via the given codec. You can use any of the string codecs or a binary codec wrapped in Base64.

Please check the codec chapter to see what codecs are available and what feature flags they require.

use leptos::prelude::*;
use serde::{Deserialize, Serialize};
use leptos_use::use_broadcast_channel;
use codee::string::JsonSerdeCodec;

// Data sent in JSON must implement Serialize, Deserialize:
#[derive(Serialize, Deserialize, Clone, PartialEq)]
pub struct MyState {
    pub playing_lego: bool,
    pub everything_is_awesome: String,
}

#[component]
fn Demo() -> impl IntoView {
use_broadcast_channel::<MyState, JsonSerdeCodec>("everyting-is-awesome");
view! { }
}

SendWrapped Return

The returned closures post and close are sendwrapped functions. They can only be called from the same thread that called use_broadcast_channel.

Feature

This function is only available if the crate feature use_broadcast_channel is enabled

Types

Source

SourceDemoDocs