JavaScript 如何实现同源通信

作者:全栈修仙之路 时间:2024-07-15 21:16:02 

    一、Broadcast Channel API 简介

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

    JavaScript 如何实现同源通信

    (图片来源 —— 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 等对象。另外,需要注意的是,在实际项目中,我们还要考虑它的兼容性:

    JavaScript 如何实现同源通信

    (图片来源 —— 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 元素的内容将会自动实现同步更新。

    JavaScript 如何实现同源通信

    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

    来源:https://mp.weixin.qq.com/s/hw_IUf7cs7YpCKvphz18Zg

    标签:JavaScript,同源通信
    0
    投稿

    猜你喜欢

  • python模块常用用法实例详解

    2023-07-30 01:38:54
  • python监控网卡流量并使用graphite绘图的示例

    2022-06-24 22:35:54
  • 前端来看看 maxthon bugs

    2008-09-23 18:35:00
  • js字符串操作方法实例分析

    2024-04-25 13:11:56
  • Python中使用装饰器来优化尾递归的示例

    2023-09-19 21:39:07
  • keras 模型参数,模型保存,中间结果输出操作

    2023-06-05 09:52:33
  • 基于FME使用Python过程图解

    2023-12-17 07:57:37
  • Python OpenCV之图片缩放的实现(cv2.resize)

    2023-01-08 14:02:48
  • pandas DataFrame创建方法的方式

    2023-03-02 11:47:52
  • 3段Python图像处理的实用代码的分享

    2021-10-19 08:06:58
  • Sql Server中的视图介绍

    2024-01-14 14:31:22
  • uniapp项目打包为桌面应用的方法步骤

    2024-04-29 13:16:04
  • 去掉CSS赘余代码,CSS可以更简洁

    2008-11-05 13:07:00
  • Python基于pip实现离线打包过程详解

    2021-09-13 06:11:08
  • ASP.NET Core基础之Startup类

    2024-05-09 09:05:07
  • Django项目之Elasticsearch搜索引擎的实例

    2022-02-26 17:30:28
  • lnmp下如何关闭Mysql日志保护磁盘空间

    2024-01-14 02:54:52
  • 基于OpenCV python3实现证件照换背景的方法

    2023-01-30 06:25:54
  • python下对hsv颜色空间进行量化操作

    2022-11-22 01:56:12
  • Sublime开发python程序的示例代码

    2023-11-06 09:45:46
  • asp之家 网络编程 m.aspxhome.com