首页
HTML&CSS
JavaScript
WebAPP
前端框架
浏览器页面通信的三个API对比介绍
## 浏览器页面通信的三个API对比介绍 - Channel Messaging API - Broadcast Channel API - postMessage ### 表格更直观 | API | 源策略 | | ------------ | ------------ | | Channel Messaging API | 同一个文档的不同浏览上下文(比如两个 iframe,或者文档主体和一个 iframe | | Broadcast Channel API | 同源的window、tab、frame 或 iframe通信 | | postMessage | 跨源通信 | ### Channel Messaging API > [Channel Messaging API](https://developer.mozilla.org/zh-CN/docs/Web/API/Channel_Messaging_API "Channel Messaging API") 允许两个运行在同一个文档的不同浏览上下文(比如两个 iframe,或者文档主体和一个 iframe,使用 SharedWorker 的两个文档,或者两个 worker)中的独立脚本直接进行通讯,在每端使用一个端口(port)通过双向频道(channel)或管道(pipe)向彼此传递消息。 *这个示例或者说这个API还没理解透* ```javascript const channel = new MessageChannel(); const para = document.querySelector("p"); const ifr = document.querySelector("iframe"); const otherWindow = ifr.contentWindow; ifr.addEventListener("load", iframeLoaded, false); function iframeLoaded() { otherWindow.postMessage("来自主页的问候!", "*", [channel.port2]); } channel.port1.onmessage = handleMessage; function handleMessage(e) { para.innerHTML = e.data; } ``` ### Broadcast Channel API > [Broadcast Channel API](https://developer.mozilla.org/zh-CN/docs/Web/API/Broadcast_Channel_API "Broadcast Channel API") 允许浏览上下文(即 window、tab、frame 或 iframe)与同源的 worker 之间进行基本通信。 ```javascript // A页面发送消息 const bc = new BroadcastChannel("test_channel"); bc.postMessage("这是一条测试消息。"); // B页面接收消息 const bc = new BroadcastChannel("test_channel"); bc.onmessage = (event) => { console.log(event); }; ``` ### postMessage > [window.postMessage()](https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage "window.postMessage()") 方法可以安全地实现跨源通信。 发送消息语法为: `otherWindow.postMessage(message, targetOrigin, [transfer]);` 接收消息语法为:`window.addEventListener("message", receiveMessage, false);` 以下是 A 窗口(或iframe)http://example-aaa.com代码: ```javascript popup.postMessage("hello there!", "http://example-bbb.com"); ``` 以下是 B 窗口(或iframe)http://example-bbb.com代码: ```javascript window.addEventListener("message", event => { if (event.origin !== "http://example-aaa.com") return; console.log(event) }, false); ``` 更多细节可参阅MDN。
2024-10-30 15:10:35
91
0
CSS 自定义高亮 API
本地IO操作之File System Access API
相关文章
Cookie Store API
本地IO操作之File System Access API
浏览器页面通信的三个API对比介绍
CSS 自定义高亮 API
汇总一下近期发现的小东西
Open Graph协议摘记-URL分享预览功能
ES2023新内容概要
漂亮的CSS移动端底部导航栏实现
CSS工作组总结的CSS设计错误
原生JS的GZIP压缩解压缩API
参与讨论
正文(*)
发表评论
选择你的头像
参与讨论