BroadCast Channel
BroadCast Channel 可以帮我们创建一个用于广播的通信频道。当所有页面都监听同一频道的消息时,其中某一个页面通过它发送的消息就会被其他所有页面收到。但是前提是同源页面。
BroadcastChannel()构造函数用于创建一个BroadcastChannel对象,并与底层的通道相关联。new BroadcastChannel(channelName)
表示通道名称的字符串;对于同源下的所有浏览上下文,一个名称只对应一个通道。
index.html
<body>
<input type="text" name="" id="content">
<button id="btn">发送数据</button>
<script>
const content = document.querySelector("#content");
const btn = document.querySelector("#btn");
// 创建一个名字是 load 的 BroadcastChannel 对象
var BroadcastChanne1 = new BroadcastChannel('load');
btn.onclick = function () {
BroadcastChanne1.postMessage({
value: content.value
});
}
</script>
</body>
index2.html
<body>
<script>
var BroadcastChanne1 = new BroadcastChannel('load');//要接收到数据,BroadcastChannel对象的名字必须相同
BroadcastChanne1.onmessage = function (e) {
console.log(e.data);//发送的数据
};
</script>
</body>
在上面的代码中,我们在页面一注册了一个名为 load 的 BroadcastChannel 对象,之后所有的页面也创建同名的 BroadcastChannel 对象,然后就可以通过 postMessage 和 onmessage 方法进行相互通信了。