JS的BroadcastChannel与MessageChannel

BroadcastChannel与MessageChannel

BroadcastChannel

BroadcastChannel以广播的形式进行通信
BroadcastChannel用于创建浏览器标签页之间的通信
使用BroadcastChannel的浏览器标签页面必须要遵循同源策略

页面1使用BroadcastChannel创建一个频道,页面2使用BroadcastChannel链接频道,页面1与页面2即可通信。

let m1=new BroadcastChannel("channel");//入参是创建或链接的频道名,没有频道则创建通信频道,有频道则进入频道
m1.postMessage('data数据');//以广播的形式向其他链接频道的标签发送消息
m1.onmessage=(e)=>{
	console.log(e);//接收频道发送过来的消息
}

实例

//BroadcastChannel1.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <a href="http://127.0.0.1:8080/BroadcastChannel2.html" target="_blank">打开新的标签页</a>
    <button onclick="send()">点击</button>
    <script>
        const m1=new BroadcastChannel('one');
        function send(){
            m1.postMessage({
                data:"123123"
            })
        }
        m1.onmessage=(e)=>{
            console.log('e=>',e);
        }
    </script>
</body>
</html>

//BroadcastChannel2.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        const m1=new BroadcastChannel('one');
        m1.onmessage=(e)=>{
            console.log("e=>",e)
        }
        m1.postMessage('adad')
    </script>
</body>
</html>

MessageChannel

MessageChannel以通道的形式进行传值
MessageChannel无法跨越浏览器标签页通信,只能在当前标签页进行通信

MessageChannel的对象只有两个端口:prot1、port2
在这里插入图片描述

let m=new MessageChannel();//创建消息通道
//m有两个端口:prot1、prot2
m.port1.postMessage("data数据");//prot1数据肯定是向prot2发送,同理prot2也只能向prot1发送数据
m.prot2.onmessage=(e)=>{
	console.log(e);//prot2接收prot1发送的数据
}

实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let m=new MessageChannel();
        m.port1.postMessage("data");
        m.port2.onmessage=(e)=>{
            console.log(e);
        }
    </script>
</body>
</html>

Tips:使用MessageChannel传递的引用数据类型是深拷贝。也就是改变端口数据的值,发送端的数据不会改变。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值