JavaScript 如何實現同源通信?
在日常工作中,你可能會遇到同源頁面間通信的場景。針對這種場景,我們可以使用 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
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/hw_IUf7cs7YpCKvphz18Zg