跨窗通信

window.postMessage()

postMessage() 是 HTML5 提供的标准 API,用户在不同窗口(包括 iframe、弹窗、标签页)之间安全地传递消息。

使用方式

// 发送方
const popup = window.open('https://example.com/page2.html');
popup.postMessage({ type: 'greeting', data: 'Hello!' }, 'https://example.com');

// 接收方,在目标窗口中监听
window.addEventListener('message', (event) => {
  // 安全检查:验证来源
  if (event.origin !== 'https://example.com') return;
  console.log('收到消息:', event.data);
});

BroadcastChannel API

BroadcastChannel 允许同源的多个浏览上下文(窗口、iframe、worker等)订阅同一个频道并广播消息。

使用方式

最后更新于

这有帮助吗?