new BroadcastChannel
BroadcastChannel 创建一个频道,可以让指定 同源下的任意浏览器来订阅它。它允许同源的不同浏览器窗口,Tab页,frame或者 iframe 下的不同文档之间相互通信。通过触发一个 message 事件,消息可以广播到所有监听了该频道的 BroadcastChannel 对象。
<button id="start-btn">开始发送</button>
<button id="end-btn">结束发送</button>
<script>
// 创建
const broadcastChannel = new BroadcastChannel('tv');
// 监听消息
broadcastChannel.onmessage = function(e) {
console.log('监听节目:', e.data);
};
document.getElementById('start-btn').onclick = function () {
// 发送消息
broadcastChannel.postMessage('发送节目');
}
document.getElementById('end-btn').onclick = function () {
// 关闭
broadcastChannel.close();
}
</script>