To implement real-time data synchronization across browser tabs, use the BroadcastChannel API or localStorage events in a service.
Using BroadcastChannel (Modern Browsers):
Create a sync service:
// sync.service.ts
@Injectable({ providedIn: 'root' })
export class SyncService {
private channel = new BroadcastChannel('app-sync');
send(data: any) {
this.channel.postMessage(data);
}
onReceive(callback: (data: any) => void) {
this.channel.onmessage = (event) => callback(event.data);
}
}
Use in components or services:
this.syncService.onReceive(data => {
console.log('Data from another tab:', data);
});
this.syncService.send({ key: 'theme', value: 'dark' });