BroadcastChannel 实现浏览器tab无刷新通讯
前提须知
- 使用
BroadcastChannel
来实现浏览器tab通讯必须是同源的 - BroadcastChannel 支持多tab间通讯
- mdn 链接
具体使用
发送方使用
<!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> <div> <button style="all: unset" onclick="onSend()">发送</button> </div> <script> /** * BroadcastChannel * 接收方和发送发必须是同源的才行进行浏览器tab的通讯 * */ const broadcast = new BroadcastChannel('music') broadcast.onmessage = (e) => { console.log(e) } function onSend() { console.log('点击了'); broadcast.postMessage({ name: 'music', data: '发送的数据' }) } </script> </body> </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> <script> const broadcast = new BroadcastChannel('music') broadcast.onmessage = ({data}) => { console.log('music接受数据了', data) } </script> </body> </html>
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 枫!