A lightweight TypeScript library for cross-tab communication using the BroadcastChannel API. This package provides a simple interface for sending and receiving messages between different browser tabs or windows.
npm install js-broadcast-channel
- 🚀 Simple and intuitive API
- 📦 TypeScript support out of the box
- 🔄 Cross-tab communication
- 🎯 Message-specific callbacks
- ⚡ Lightweight with zero dependencies
- 🎭 Built-in message handlers and lifecycle hooks
import { BroadcastJS } from 'js-broadcast-channel';
// Initialize BroadcastJS with a channel name
const broadcast = new BroadcastJS('my-channel');
// Send a message
broadcast.postMessage({
message: 'update-count',
data: { count: 42 }
});
// Listen for messages
broadcast.onMessage('update-count', (message) => {
console.log('Received count:', message.data.count);
});
new BroadcastJS(name: string, handlers?: BroadcastHandlers)
-
onBeforeSendMessage
: Called before a message is sent -
onAfterSendMessage
: Called after a message is sent -
onBeforePostMessage
: Called before posting a message -
onAfterPostMessage
: Called after posting a message -
onBeforeClose
: Called before closing the channel -
onAfterClose
: Called after closing the channel -
onError
: Called when an error occurs
Sends a message to all other tabs/windows listening on the same channel.
interface Message<T = unknown> {
message: string;
data: T;
}
Registers a callback for a specific message type.
Closes the broadcast channel and cleans up resources.
Checks if there are any listeners for a specific message.
Checks if the browser supports the BroadcastChannel API.
Removes a message listener.
const broadcast = new BroadcastJS('my-channel', {
onBeforeSendMessage: (message) => {
console.log('About to send:', message);
},
onAfterSendMessage: (message) => {
console.log('Message sent:', message);
},
onError: (message) => {
console.error('Error processing message:', message);
}
});
This package requires browser support for the BroadcastChannel API. Check Can I Use for browser compatibility.
Contributions are welcome! Please feel free to submit a Pull Request.
ISC
Alireza Valipour