useBroadcastChannel ​
that provides cross-tab/window communication
browser
test coverage
Last changed: 4 minutes ago
TIP
This hook uses BroadcastChannel browser api to provide enhanced functionality. Make sure to check for compatibility with different browsers when using this api
Installation ​
Library
CLI
Manual
typescript
import { useBroadcastChannel } from '@siberiacancode/reactuse';
Usage ​
typescript
const { supported, data, post, error } = useBroadcastChannel('channel');
Demo ​
Api ​
Parameters
Name | Type | Default | Note |
---|---|---|---|
name | string | - | The name of the channel |
callback | Function | - | A callback function that will be called when a message is received |
Returns
UseBroadcastChannelReturn
Type declaration ​
typescript
export interface UseBroadcastChannelReturn<Data = unknown> {
/** The underlying BroadcastChannel instance if supported, undefined otherwise */
channel?: BroadcastChannel;
/** Whether the channel has been closed */
closed: boolean;
/** The most recently received data from other contexts */
data?: Data;
/** Error object if any error occurred during channel operations */
error?: Event;
/** Whether the BroadcastChannel API is supported in the current environment */
supported: boolean;
/** Function to close the channel and clean up resources */
close: () => void;
/** Function to send data to other contexts through the channel */
post: (data: Data) => void;
}
Source ​
Source • DemoContributors ​
D