当前位置: 首页 > news >正文

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传递的引用数据类型是深拷贝。也就是改变端口数据的值,发送端的数据不会改变。

http://www.lryc.cn/news/35939.html

相关文章:

  • nextjs开发 + vercel 部署 ssr ssg
  • Good Idea, 利用MySQL JSON特性优化千万级文库表
  • 【python游戏制作】快来跟愤怒的小鸟一起攻击肥猪们的堡垒吧
  • ARM 学习(一)
  • 深入分析Java的序列化与反序列化
  • 、Tomcat源码分析-类加载器
  • 反转链表相关的练习(下)
  • 2.进程和线程
  • C++回顾(十四)—— 函数模板
  • 如何做好项目各干系人的管理及应对?
  • Elasticsearch使用系列-ES增删查改基本操作+ik分词
  • 07-PL/SQL基础(if语句,case语句,循环语句)
  • 信捷 XDH Ethercat A_VELMOVE
  • 【专项训练】分治、回溯
  • Linux上安装配置ZooKeeper
  • idea leetcode插件无法登录
  • VR会议不断升级,为商务会谈打造云端洽谈服务!
  • Ubuntu系统开机自动挂载NTFS硬盘【超实用】
  • 淘宝十年资深架构师吐血总结淘宝的数据库架构设计和采用的技术手段。
  • 训练自己的GPT2-Chinese模型
  • springcloud3 fegin服务超时的配置和日志级别的配置2
  • 华为机试 HJ48 从单向链表中删除指定值的节点
  • 华为机试 HJ1 字符串最后一个单词的长度
  • 从入门到精通MongoDB数据库系列之二:深入了解MongoDB基本概念文档、集合、数据库、数据类型、MongoDB shell
  • 前端实用技巧,JS压缩、美化、JS混淆加密
  • synchronized轻量级锁优化
  • python 日期转换 日期字符相关
  • 使用sm4js进行加密和国密sm4的总结
  • c语言面试题目整理
  • 【嵌入式Bluetooth应用开发笔记】第三篇:初探BLUE ALSA应用开发