BroadcastChannel
Simple same-origin pub/sub between tabs, windows, iframes and workers: post a message on a named channel and every other listener on that channel receives it.
@inject Bit.Butil.BroadcastChannel broadcastChannelMDN reference
Returns true when the runtime exposes BroadcastChannel. The API is available in every modern browser and requires no permissions.
var supported = await broadcastChannel.IsSupported();Subscribes to a named channel. Every message arrives as a JsonElement so you can deserialize into whatever shape you expect; the optional onError callback fires on a messageerror event (a payload that could not be deserialized). One BroadcastChannel instance can host any number of named channels - the JS-side channel is created on first subscribe per name and torn down when its last subscription is disposed.
var subscription = await broadcastChannel.Subscribe("butil-demo",
onMessage: data =>
{
// data is a JsonElement - e.g. data.GetString() for plain text
},
onError: () =>
{
// a message on the channel failed to deserialize
});
// later, to detach:
await subscription.DisposeAsync();Sends a message to every other listener on the channel within the same origin. Any JSON-serializable value works - strings, numbers or whole objects. Remember: the sender itself does not receive the message, so watch the console of the other tab.
await broadcastChannel.Post("butil-demo", "Hello, other tabs!");
// objects work too:
await broadcastChannel.Post("butil-demo", new { user = "alice", action = "signed-in" });API reference
ValueTask<bool> IsSupported()ValueTask Post<T>(string channelName, T message)Task<ButilSubscription> Subscribe(string channelName, Action<JsonElement>? onMessage, Action? onError = null)ValueTask DisposeAsync()void InvokeBroadcastChannelMessage(Guid id, JsonElement data)void InvokeBroadcastChannelError(Guid id)