亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

JavaScript 如何實(shí)現(xiàn)同源通信

 更新時(shí)間:2021年05月13日 14:15:37   作者:全棧修仙之路  
在日常工作中,你可能會(huì)遇到同源頁(yè)面間通信的場(chǎng)景。針對(duì)這種場(chǎng)景,我們可以使用 localStorage 和 storage 事件來(lái)解決同源頁(yè)面間通信的問(wèn)題。除此之外,我們還可以使用 Broadcast Channel API 來(lái)解決該問(wèn)題。接下來(lái),將帶大家一起來(lái)認(rèn)識(shí)一下 Broadcast Channel API。

一、Broadcast Channel API 簡(jiǎn)介

Broadcast Channel API 可以實(shí)現(xiàn)同源下瀏覽器不同窗口、Tab 頁(yè)或者 iframe 下的瀏覽器上下文之間的簡(jiǎn)單通訊。通過(guò)創(chuàng)建一個(gè)監(jiān)聽(tīng)某個(gè)頻道下的 BroadcastChannel 對(duì)象,你可以接收發(fā)送給該頻道的所有消息。

(圖片來(lái)源 —— https://developer.mozilla.org/zh-CN/docs/Web/API/Broadcast_Channel_API

了解完 Broadcast Channel API 的作用之后,我們來(lái)看一下如何使用它:

// 創(chuàng)建一個(gè)用于廣播的通信通道
const channel = new BroadcastChannel('my_bus');

// 在my_bus上發(fā)送消息
channel.postMessage('大家好,我是阿寶哥');

// 監(jiān)聽(tīng)my_bus通道上的消息
channel.onmessage = function(e) {
  console.log('已收到的消息:', e.data);
};

// 關(guān)閉通道
channel.close();

通過(guò)觀察以上示例,我們可以發(fā)現(xiàn) Broadcast Channel API 使用起來(lái)還是很簡(jiǎn)單的。該 API 除了支持發(fā)送字符串之外,我們還可以發(fā)送其它對(duì)象,比如 Blob、File、ArrayBuffer、Array 等對(duì)象。另外,需要注意的是,在實(shí)際項(xiàng)目中,我們還要考慮它的兼容性:

(圖片來(lái)源 —— https://caniuse.com/?search=Broadcast%20Channel%20API

由上圖可知,在 IE 11 及以下的版本,是不支持 Broadcast Channel API,這時(shí)你就可以考慮使用現(xiàn)成的 broadcast-channel-polyfill 或者基于 localStorage 和 storage 事件來(lái)實(shí)現(xiàn)。

二、Broadcast Channel API 應(yīng)用場(chǎng)景

利用 Broadcast Channel API,我們可以輕易地實(shí)現(xiàn)同源頁(yè)面間一對(duì)多的通信。該 API 的一些使用場(chǎng)景如下:

  • 實(shí)現(xiàn)同源頁(yè)面間數(shù)據(jù)同步;
  • 在其它 Tab 頁(yè)面中監(jiān)測(cè)用戶操作;
  • 指導(dǎo) worker 執(zhí)行一個(gè)后臺(tái)任務(wù);
  • 知道用戶何時(shí)登錄另一個(gè) window/tab 中的帳戶。

為了讓大家能夠更好地掌握 Broadcast Channel API,阿寶哥以前面 2 個(gè)使用場(chǎng)景為例,來(lái)介紹一下該 API 的具體應(yīng)用。

2.1 實(shí)現(xiàn)同源頁(yè)面間數(shù)據(jù)同步

html

<h3 id="title">你好,</h3>
<input id="userName" placeholder="請(qǐng)輸入你的用戶名" />

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("請(qǐng)告訴我們你的用戶名");
  }

  userName.onchange = (e) => {
    const inputValue = e.target.value;
    localStorage.setItem("title", inputValue);
    setTitle(inputValue);
    bc.postMessage("update_title");
  };
})();

在以上示例中,我們實(shí)現(xiàn)了同源頁(yè)面間的數(shù)據(jù)同步。當(dāng)任何一個(gè)已打開(kāi)的頁(yè)面中,輸入框的數(shù)據(jù)發(fā)生變化時(shí),頁(yè)面中的 h3#title 元素的內(nèi)容將會(huì)自動(dòng)實(shí)現(xiàn)同步更新。

2.2 在其它 Tab 頁(yè)面中監(jiān)測(cè)用戶操作

利用 Broadcast Channel API,除了可以實(shí)現(xiàn)同源頁(yè)面間的數(shù)據(jù)同步之外,我們還可以利用它來(lái)實(shí)現(xiàn)在其它 Tab 頁(yè)面中監(jiān)測(cè)用戶操作的功能。比如,當(dāng)用戶在任何一個(gè) Tab 中執(zhí)行退出操作后,其它已打開(kāi)的 Tab 頁(yè)面也能夠自動(dòng)實(shí)現(xiàn)退出,從而保證系統(tǒng)的安全性。

html

<h3 id="status">當(dāng)前狀態(tài):已登錄</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 = "當(dāng)前狀態(tài):已退出";
}

在以上示例中,當(dāng)用戶點(diǎn)擊退出按鈕后,當(dāng)前頁(yè)面會(huì)執(zhí)行退出操作,同時(shí)會(huì)通過(guò) logoutChannel 通知其它已打開(kāi)的頁(yè)面執(zhí)行退出操作。

三、Broadcast Channel API vs postMessage API

與 postMessage() 不同的是,你不再需要維護(hù)對(duì) iframe 或 worker 的引用才能與其進(jìn)行通信:

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

Broadcast Channel API 只能用于實(shí)現(xiàn)同源下瀏覽器不同窗口、Tab 頁(yè)或者 iframe 下的瀏覽器上下文之間的簡(jiǎn)單通訊。而 postMessage API 卻可用于實(shí)現(xiàn)不同源之間消息通信。由于保證消息來(lái)自同一來(lái)源,因此無(wú)需像以前那樣使用以下方法來(lái)驗(yàn)證消息:

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

四、總結(jié)

Broadcast Channel API 是一個(gè)非常簡(jiǎn)單的 API,內(nèi)部包含了跨上下文通訊的接口。在支持該 API 的瀏覽器中,我們可以利用該 API 輕松地實(shí)現(xiàn)同源頁(yè)面間的通信。而對(duì)于不支持該 API 的瀏覽器來(lái)說(shuō),我們就可以考慮使用 localStorage 和 storage 事件來(lái)解決同源頁(yè)面間通信的問(wèn)題。

五、參考資源

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

以上就是JavaScript 如何實(shí)現(xiàn)同源通信的詳細(xì)內(nèi)容,更多關(guān)于JavaScript 同源通信的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論