同源同窗口 (window.opener / parent / top)
// 頁面 A (打開頁面 B)
const winB = window.open('pageB.html');
winB.addEventListener('load', () => {
winB.document.getElementById('btn').addEventListener('click', () => {
console.log('頁面 B 按鈕被點擊');
});
});
// 或頁面 B 主動通知
// 頁面 B
window.opener.postMessage({type: 'btn_click'}, '*');
// 頁面 A
window.addEventListener('message', e => {
if (e.data.type === 'btn_click') console.log('收到點擊');
});
跨域/不同標籤頁
- LocalStorage + storage 事件:頁面 B `localStorage.setItem('btn_click', Date.now())`,頁面 A 監聽 `storage` 事件。
- BroadcastChannel API** (現代):
const ch = new BroadcastChannel('app_channel');
ch.postMessage({type: 'btn_click'}); // 發送
ch.onmessage = e => console.log(e.data); // 接收
- Service Worker / SharedWorker** 傳遞訊息。
- 後端輪詢/WebSocket** 萬能但較重。
選擇建議
| 場景 | 方案 |
| 同源 window.open | 直接 DOM 訪問 / postMessage |
| 同源不同標籤 | BroadcastChannel / LocalStorage |
| 跨域 iframe | postMessage (指定 origin) |
| 完全獨立頁面 | 後端狀態同步 (DB/Redis + 輪詢/WS) |