您现在的位置是:亿华云 > 系统运维

JavaScript 如何实现同源通信?

亿华云2025-10-03 06:15:53【系统运维】6人已围观

简介在日常工作中,你可能会遇到同源页面间通信的场景。针对这种场景,我们可以使用 localStorage 和 storage 事件来解决同源页面间通信的问题。除此之外,我们还可以使用 Broadcast

在日常工作中,何实你可能会遇到同源页面间通信的现同信场景。针对这种场景,源通我们可以使用 localStorage 和 storage 事件来解决同源页面间通信的何实问题。除此之外,现同信我们还可以使用 Broadcast Channel API 来解决该问题。源通接下来,何实阿宝哥将带大家一起来认识一下 Broadcast Channel API。现同信

一、源通Broadcast Channel API 简介

Broadcast Channel API 可以实现同源下浏览器不同窗口、何实Tab 页或者 iframe 下的现同信浏览器上下文之间的简单通讯。通过创建一个监听某个频道下的源通 BroadcastChannel 对象,你可以接收发送给该频道的何实所有消息。

(图片来源 —— https://developer.mozilla.org/zh-CN/docs/Web/API/Broadcast_Channel_API)

了解完 Broadcast Channel API 的现同信作用之后,我们来看一下如何使用它:

// 创建一个用于广播的源通通信通道 const channel = new BroadcastChannel(my_bus); // 在my_bus上发送消息 channel.postMessage(大家好,我是阿宝哥); // 监听my_bus通道上的消息 channel.onmessage = function(e) {    console.log(已收到的消息:, e.data); }; // 关闭通道 channel.close(); 

通过观察以上示例,我们可以发现 Broadcast Channel API 使用起来还是很简单的。该 API 除了支持发送字符串之外,我们还可以发送其它对象,比如 Blob、File、网站模板ArrayBuffer、Array 等对象。另外,需要注意的是,在实际项目中,我们还要考虑它的兼容性: 

(图片来源 —— https://caniuse.com/?search=Broadcast%20Channel%20API)

由上图可知,在 IE 11 及以下的版本,是不支持 Broadcast Channel API,这时你就可以考虑使用现成的 broadcast-channel-polyfill 或者基于 localStorage 和 storage 事件来实现。

二、Broadcast Channel API 应用场景

利用 Broadcast Channel API,我们可以轻易地实现同源页面间一对多的通信。该 API 的一些使用场景如下:

实现同源页面间数据同步; 在其它 Tab 页面中监测用户操作; 指导 worker 执行一个后台任务; 知道用户何时登录另一个 window/tab 中的帐户。

为了让大家能够更好地掌握 Broadcast Channel API,阿宝哥以前面 2 个使用场景为例,来介绍一下该 API 的具体应用。

2.1 实现同源页面间数据同步

html

<h3 id="title">你好,</h3> <input id="userName" placeholder="请输入你的用户名" /> 

 JS

const bc = new BroadcastChannel("abao_channel"); (() => {    const title = document.querySelector("#title");   const userName = document.querySelector("#userName");   const setTitle = (userName) => {      title.innerHTML = "你好," + userName;   };   bc.onmessage = (messageEvent) => {      if (messageEvent.data === "update_title") {        setTitle(localStorage.getItem("title"));     }   };   if (localStorage.getItem("title")) {      setTitle(localStorage.getItem("title"));   } else {      setTitle("请告诉我们你的用户名");   }   userName.onchange = (e) => {      const inputValue = e.target.value;     localStorage.setItem("title", inputValue);     setTitle(inputValue);     bc.postMessage("update_title");   }; })(); 

在以上示例中,我们实现了同源页面间的数据同步。源码下载当任何一个已打开的页面中,输入框的数据发生变化时,页面中的 h3#title 元素的内容将会自动实现同步更新。

2.2 在其它 Tab 页面中监测用户操作

利用 Broadcast Channel API,除了可以实现同源页面间的数据同步之外,我们还可以利用它来实现在其它 Tab 页面中监测用户操作的功能。比如,当用户在任何一个 Tab 中执行退出操作后,其它已打开的 Tab 页面也能够自动实现退出,从而保证系统的安全性。

html

<h3 id="status">当前状态:已登录</h3> <button onclick="logout()">退出</button> 

 JS

const status = document.querySelector("#status"); const logoutChannel = new BroadcastChannel("logout_channel"); logoutChannel.onmessage = function (e) {    if (e.data.cmd === "logout") {      doLogout();   } }; function logout() {    doLogout();   logoutChannel.postMessage({  cmd: "logout", user: "阿宝哥" }); } function doLogout() {    status.innerText = "当前状态:已退出"; } 

在以上示例中,当用户点击退出按钮后,当前页面会执行退出操作,同时会通过 logoutChannel 通知其它已打开的页面执行退出操作。

三、Broadcast Channel API vs postMessage API

与 postMessage() 不同的是,你不再需要维护对 iframe 或 worker 的引用才能与其进行通信:

const popup = window.open(https://another-origin.com, ...); popup.postMessage(Sup popup!, https://another-origin.com); 

Broadcast Channel API 只能用于实现同源下浏览器不同窗口、Tab 页或者 iframe 下的浏览器上下文之间的简单通讯。而 postMessage API 却可用于实现不同源之间消息通信。源码库由于保证消息来自同一来源,因此无需像以前那样使用以下方法来验证消息:

const iframe = document.querySelector(iframe); iframe.contentWindow.onmessage = function(e) {    if (e.origin !== https://expected-origin.com) {      return;   }   e.source.postMessage(Ack!, e.origin); }; 

 四、总结

Broadcast Channel API 是一个非常简单的 API,内部包含了跨上下文通讯的接口。在支持该 API 的浏览器中,我们可以利用该 API 轻松地实现同源页面间的通信。而对于不支持该 API 的浏览器来说,我们就可以考虑使用 localStorage 和 storage 事件来解决同源页面间通信的问题。

五、参考资源

MDN - Broadcast Channel API BroadcastChannel API: A Message Bus for the Web

很赞哦!(263)