Broadcast Channel API는 같은 출처의 여러 탭, 창, 프레임, Worker 간에 메시지를 브로드캐스트하는 Web API다. localStorage 이벤트보다 명확하고 양방향 통신이 가능하다.
기본 사용법
javascript
// 채널 생성 (같은 이름 = 같은 채널)
const channel = new BroadcastChannel('app-updates');
// 메시지 전송 (모든 같은 출처 컨텍스트에 전달)
channel.postMessage({
type: 'user-login',
userId: 1001,
timestamp: Date.now()
});
// 메시지 수신
channel.onmessage = (event) => {
const { type, userId } = event.data;
if (type === 'user-login') {
console.log(`User ${userId} logged in`);
updateUIForLogin(userId);
}
};
// 또는 addEventListener
channel.addEventListener('message', handler);
// 채널 닫기
channel.close();
실제 활용 패턴
javascript
// 패턴 1: 로그아웃 동기화 (모든 탭)
// auth.js
const authChannel = new BroadcastChannel('auth');
function logout() {
clearSession();
authChannel.postMessage({ type: 'logout' });
window.location.href = '/login';
}
authChannel.onmessage = ({ data }) => {
if (data.type === 'logout') {
clearSession();
window.location.href = '/login';
}
};
// 패턴 2: 캐시 무효화 (Service Worker → 탭)
// service-worker.js
const sw = new BroadcastChannel('sw-updates');
sw.postMessage({ type: 'cache-updated', version: '2.0.0' });
// app.js
const updateChannel = new BroadcastChannel('sw-updates');
updateChannel.onmessage = ({ data }) => {
if (data.type === 'cache-updated') {
showReloadPrompt(data.version);
}
};
// 패턴 3: 탭 간 상태 동기화
const stateChannel = new BroadcastChannel('app-state');
stateChannel.postMessage({ type: 'cart-updated', items: cartItems });
BroadcastChannel vs 다른 탭 간 통신
| 방법 | 방향 | 범위 | 복잡도 |
|---|
| BroadcastChannel | 1:N | 같은 출처 | 낮음 |
| localStorage 이벤트 | 1:N | 같은 출처 | 낮음 (단방향) |
| SharedWorker | N:N | 같은 출처 | 중간 |
| postMessage | 1:1 | iframe/popup | 중간 |
| Service Worker | 1:N | 등록된 페이지 | 높음 |
관련 문서