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::*;
use leptos_use::{use_broadcast_channel, UseBroadcastChannelReturn};
use leptos_use::utils::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! { }
}

Just like with use_storage you can use different codecs for encoding and decoding.

use leptos::*;
use serde::{Deserialize, Serialize};
use leptos_use::use_broadcast_channel;
use leptos_use::utils::JsonCodec;

// 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, JsonCodec>("everyting-is-awesome");
view! { }
}

Create Your Own Custom Codec

All you need to do is to implement the StringCodec trait together with Default and Clone.

Types

Source

SourceDemoDocs