🚀 The simplest way to sync data between browser tabs! A tiny yet powerful library that makes tab communication a breeze.
- 🪶 Incredibly Light - Tiny 4KB footprint with zero dependencies. Your bundle size will thank you!
- 🔄 Seamless Sync - Keep your tabs in perfect harmony. Update data in one tab, see it everywhere!
- 📨 Easy Communication - Let your tabs talk to each other like best friends
- 💾 Smart Management - Handle your data with ease. Auto-persists state across page refreshes!
- 🔐 Auto Persistence - Your data survives refreshes and tab closures. Never lose state again!
npm install tab-syncer
# or
yarn add tab-syncer
import { TabSyncer } from 'tab-syncer';
// Initialize TabSync with a unique namespace and initial state
const tabSyncer = new TabSyncer(
'myApp', // namespace
'broadcast', // sync method
{ // initial state
count: 0,
message: ''
}
);
// Update state
tabSyncer.setState(prevState => ({
...prevState,
count: prevState.count + 1
}));
// Get current state
const state = tabSync.getState();
// Listen to state changes
tabSyncer.onStateChange((state) => {
console.log('State updated:', state);
});
// Send notifications across tabs
tabSyncer.notify('customEvent', { data: 'Hello from another tab!' });
// Subscribe to notifications
tabSyncer.subscribe('customEvent', (data) => {
console.log('Received:', data);
});
Creates a new TabSyncer instance.
new TabSyncer(
namespace: string, // Unique identifier for your app instance
method: string, // Sync method, currently supports 'broadcast'
initialState: T // Initial state object of any type
)
Updates the state across all tabs.
Type:
setState(newState: T | ((prevState: T) => T)): void
Example:
// Direct value
tabSyncer.setState({ count: 1, message: 'Hello' });
// Updater function
tabSyncer.setState(prevState => ({
...prevState,
count: prevState.count + 1
}));
Returns the current state.
Type:
getState(): T
Example:
const currentState = tabSyncer.getState();
console.log(currentState); // { count: 1, message: 'Hello' }
Subscribe to state changes across all tabs.
Type:
onStateChange(callback: (state: T) => void): () => void
Example:
const unsubscribe = tabSyncer.onStateChange((state) => {
console.log('New state:', state);
});
// Cleanup when needed
unsubscribe();
Send a custom event to all other tabs.
Type:
notify(event: string, data: any): void
Example:
tabSyncer.notify('userLoggedIn', {
userId: 123,
timestamp: Date.now()
});
Listen for custom events from other tabs.
Type:
subscribe(event: string, callback: (data: any) => void): () => void
Example:
const unsubscribe = tabSyncer.subscribe('userLoggedIn', (data) => {
console.log('User logged in from another tab:', data);
});
// Cleanup when needed
unsubscribe();
MIT