2026/5/18 21:37:27
网站建设
项目流程
中山技术支持中山网站建设,如何用 python 做网站,九江专业网站建设定制,竹子建站免费版前情平时开发很少有接触到有什么需求需要实现跨标签页通信#xff0c;但最近因为一些变故#xff0c;不得不重新开始找工作了#xff0c;其中就有面试官问到一道题#xff0c;跨标签页怎么实现数据通信#xff0c;我当时只答出二种#xff0c;面试完后特意重新查资料但最近因为一些变故不得不重新开始找工作了其中就有面试官问到一道题跨标签页怎么实现数据通信我当时只答出二种面试完后特意重新查资料因此有些文章localStorage / sessionStorage利用localStorage的存储事件实现通信当一个标签页修改localStorage时其他同源标签页会触发storage事件关键代码如下标签页1!DOCTYPE htmlhtml langenheadmeta charsetUTF-8meta nameviewport contentwidthdevice-width, initial-scale1.0titlepage0-localStorage/title/headbodybutton idsetCacheBtn设置本地缓存/buttonscriptdocument.getElementById(setCacheBtn).addEventListener(click, () {localStorage.setItem(message, JSON.stringify({type: greeting,// 这里为了保证通信每次生效每次都设置不同的值content: Hello from page0.html Date.now()}));});/script/body/html标签页2!DOCTYPE htmlhtml langenheadmeta charsetUTF-8meta nameviewport contentwidthdevice-width, initial-scale1.0titlepage1-localStorage/title/headbodyscriptwindow.addEventListener(storage, (e) {if (e.key message) {const data JSON.parse(e.newValue);console.log(Received:page1.html, data);}});/script/body/html动图演示20250923_193504提醒同源标签才有效设置不同的本地存储值才有效如果设置的是同一个缓存值是不会生效的兼容性非常nice可以大胆使用了国内一些浏览器从can i use查不到但兼容性是没啥问题的sessionStorage仅在同一标签页的不同 iframe 间有效不适用于不同标签页imageBroadcastChannel专门用于同源标签页通信的 API创建一个频道后所有加入该频道的页面都能收到消息关键代码如下:标签页1!DOCTYPE htmlhtml langenheadmeta charsetUTF-8meta nameviewport contentwidthdevice-width, initial-scale1.0titleBroadcastChannel0/title/headbodyh1BroadcastChannel0/h1button idcommunicationBroadcastChannel0.html 发送消息/buttonscript// 所有页面都创建相同名称的频道const channel new BroadcastChannel(my_channel);// 发送消息document.getElementById(communication).addEventListener(click, () {channel.postMessage({ type: update, data: new content from BroadcastChannel0.html });});/script/body/html标签页2!DOCTYPE htmlhtml langenheadmeta charsetUTF-8meta nameviewport contentwidthdevice-width, initial-scale1.0titleBroadcastChannel1/title/headbodyh1BroadcastChannel1/h1script// 所有页面都创建相同名称的频道const channel new BroadcastChannel(my_channel);// 接收消息channel.onmessage (e) {console.log(Received:BroadcastChannel1.html, e.data);};/script/body/html演示动图如下20250923_200047提醒要通信的标签记得都初始化BroadcastChannel一定记得使用相同的名称查询来看除IE外可以大但使用了image 1小结这二种是我面试的时候答出来的第二种我只是模糊记得跟面试官模棱二可的说了说面试馆给了正面的回应呵呵……此文暂时写这么多下篇继续探索其它方式……