浏览器不同窗口通信-BroadcastChannel

121 阅读1分钟

最近老板让我做一个多个页面同步更新的需求,我就想到了BroadcastChannel

1.BroadcastChannel是什么?

web api的其中一个。

2.BroadcastChannel的作用?

用于同源的不同页面之间进行通信。

3.BroadcastChannel的限制?

一定要同源情况下。

4.demo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button onclick="sends()">BroadcastChannel发送</button>
</body>
<script>
    const c = new BroadcastChannel('testChannel')
    function sends(){
        console.info('已发送')
        c.postMessage('同源 发送消息')
    }
</script>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
<script>
    const c = new BroadcastChannel('testChannel')
    c.onmessage=(e)=>{
        console.info('接收信息BroadcastChannel:',e.data)
    }
</script>
</html>

a.html点击发送消息

image.png

b.html 不用任何操作就可以接收消息

image.png

提到postMessage:

说到 BroadCast Channel 不得不说一下 postMessage,他们二者的最大区别就在于 postMessage 更像是点对点的通信,而 BroadCast Channel 是广播的方式,点到面。

每个 BroadcastChannel 对象都需要使用一个唯一的名称来标识通道,这个名称在同一域名下的不同页面之间必须是唯一的,它允许同一域名下的不同页面之间进行通信。

通过 postMessage 方法,一个页面可以将消息发送到频道中,而其他页面则可以监听 message 事件来接收这些消息。

通过这种方式是短线了一种实时通信的机制,可以在不同的页面之间传递信息,实现页面间的即时交流。

这种方式的优点是非常灵活,可以在不同的窗口之间进行双向通信,并且可以跨越不同的域。

但需要注意的是,由于跨域通信涉及到安全性问题,因此在使用时需要特别小心,确保不会因为跨域通信而引入安全隐患。

因此,这种方法只适用于通过window.open()或document.open()打开的浏览器标签页。