专业的网站建设哪家快,电子商务智能建站,什么是网络营销培训,濮阳市城乡一体化示范区范围目前浏览器跨标签页通信的方式有很多#xff0c;比如#xff1a;websocket、针对LocalStorage使用window.onstorage、window.postmessage。 本文将用BroadcastChannel实现同一域名下两个标签页间消息的收和发 一、全局创建通信通道
const channel new BroadcastChannel(cha… 目前浏览器跨标签页通信的方式有很多比如websocket、针对LocalStorage使用window.onstorage、window.postmessage。 本文将用BroadcastChannel实现同一域名下两个标签页间消息的收和发 一、全局创建通信通道
const channel new BroadcastChannel(channel1);二、发送消息与监听消息
const sendMsg (type, msg) {channel.postMessage({type,msg,});
};const listen (callback) {channel.addEventListener(message, (e) {console.log(eee, e);callback(e.data);});
}三、应用
触发事件
const handleClick () {sendMsg(add, { name: 张三, age: 22 });
}接受消息处理业务逻辑
listen((data) {console.log(data, data);const { type, msg } data;if (type add) {const h1 document.querySelector(h1);h1.append(姓名${msg.name}-年龄${msg.age});}
});演示
使用Live Server启动本地演示项目两个标签页打开同一个页面一个发一个收 channel 源码
!DOCTYPE html
html langen
headmeta charsetUTF-8meta nameviewport contentwidthdevice-width, initial-scale1.0titleDocument/title
/head
bodyscript src./channel.js/scriptscript src./index.js/scriptbutton onclickhandleClick(event)发送/buttonh1/h1
/body
/html// channel.jsconst channel new BroadcastChannel(channel1);const sendMsg (type, msg) {channel.postMessage({type,msg,});
};const listen (callback) {channel.addEventListener(message, (e) {console.log(eee, e);callback(e.data);});
}// index.jslisten((data) {console.log(data, data);const { type, msg } data;if (type add) {const h1 document.querySelector(h1);h1.append(姓名${msg.name}----年龄${msg.age});}
});const handleClick () {sendMsg(add, { name: 张三, age: 22 });
}