吉林省建设部网站,wordpress主题 大前端 阿里百秀 xiu,哈尔滨论坛建站模板,移动 网站模板BroadcastChannel与MessageChannel
BroadcastChannel
BroadcastChannel以广播的形式进行通信 BroadcastChannel用于创建浏览器标签页之间的通信 使用BroadcastChannel的浏览器标签页面必须要遵循同源策略
页面1使用BroadcastChannel创建一个频道#xff0c;页面2使用Broadc…BroadcastChannel与MessageChannel
BroadcastChannel
BroadcastChannel以广播的形式进行通信 BroadcastChannel用于创建浏览器标签页之间的通信 使用BroadcastChannel的浏览器标签页面必须要遵循同源策略
页面1使用BroadcastChannel创建一个频道页面2使用BroadcastChannel链接频道页面1与页面2即可通信。
let m1new BroadcastChannel(channel);//入参是创建或链接的频道名没有频道则创建通信频道有频道则进入频道
m1.postMessage(data数据);//以广播的形式向其他链接频道的标签发送消息
m1.onmessage(e){console.log(e);//接收频道发送过来的消息
}实例
//BroadcastChannel1.html
!DOCTYPE html
html langen
headmeta charsetUTF-8meta http-equivX-UA-Compatible contentIEedgemeta nameviewport contentwidthdevice-width, initial-scale1.0titleDocument/title
/head
bodya hrefhttp://127.0.0.1:8080/BroadcastChannel2.html target_blank打开新的标签页/abutton onclicksend()点击/buttonscriptconst m1new BroadcastChannel(one);function send(){m1.postMessage({data:123123})}m1.onmessage(e){console.log(e,e);}/script
/body
/html//BroadcastChannel2.html
!DOCTYPE html
html langen
headmeta charsetUTF-8meta http-equivX-UA-Compatible contentIEedgemeta nameviewport contentwidthdevice-width, initial-scale1.0titleDocument/title
/head
bodyscriptconst m1new BroadcastChannel(one);m1.onmessage(e){console.log(e,e)}m1.postMessage(adad)/script
/body
/htmlMessageChannel
MessageChannel以通道的形式进行传值 MessageChannel无法跨越浏览器标签页通信只能在当前标签页进行通信
MessageChannel的对象只有两个端口prot1、port2
let mnew MessageChannel();//创建消息通道
//m有两个端口prot1、prot2
m.port1.postMessage(data数据);//prot1数据肯定是向prot2发送同理prot2也只能向prot1发送数据
m.prot2.onmessage(e){console.log(e);//prot2接收prot1发送的数据
}实例
!DOCTYPE html
html langen
headmeta charsetUTF-8meta http-equivX-UA-Compatible contentIEedgemeta nameviewport contentwidthdevice-width, initial-scale1.0titleDocument/title
/head
bodyscriptlet mnew MessageChannel();m.port1.postMessage(data);m.port2.onmessage(e){console.log(e);}/script
/body
/htmlTips使用MessageChannel传递的引用数据类型是深拷贝。也就是改变端口数据的值发送端的数据不会改变。