JavaScript 如何实现同源通信?



JavaScript 如何实现同源通信?

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

一、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"); 

  }; 

})(); 




上一篇:原代培养方法技术
下一篇:吉林油田“靶向”施策提质提效