BroadcastChannel API - 網路訊息匯流排

BroadcastChannel API 允許相同來源的指令碼將訊息傳送至其他瀏覽環境。這可以視為簡單的訊息匯流排,可在視窗/分頁、iframe、Web 工作人員和服務 Worker 之間進行 Pub/Sub 語意。

API 基本資訊

Broadcast Channel API 是一種簡單的 API,可簡化瀏覽環境之間的通訊。也就是視窗/分頁、iframe、網路工作站和服務工作站之間的通訊。發布至特定頻道的訊息會傳送給該頻道的所有聽眾。

BroadcastChannel 建構函式使用單一參數:管道名稱。 名稱可用來識別頻道和各種瀏覽環境。

// Connect to the channel named "my_bus".
const channel = new BroadcastChannel('my_bus');

// Send a message on "my_bus".
channel.postMessage('This is a test message.');

// Listen for messages on "my_bus".
channel.onmessage = function(e) {
    console.log('Received', e.data);
};

// Close the channel when you're done.
channel.close();

傳送訊息

訊息可以是字串,或結構化本機副本演算法支援的任何項目 (String、Objects、Arrays、Blobs、ArrayBuffer、Map)。

範例 - 傳送 Blob 或檔案

channel.postMessage(new Blob(['foo', 'bar'], {type: 'plain/text'}));

頻道不會向自己播送。如果您有 onmessage 事件監聽器 與 postMessage() 在同一頁面上、該 message 事件 都不會觸發

與其他技術的差異

現在您可能想知道,這與其他傳遞訊息的技術相關,例如 WebSocket、SharedWorkers、MessageChannel APIwindow.postMessage()。Broadcast Channel API 不會取代這些 API。兩者都有各自的用途Broadcast Channel API 適合用來在「相同來源」上的指令碼之間輕鬆進行一對多通訊。

廣播頻道的幾項用途:

  • 偵測其他分頁中的使用者動作
  • 得知使用者在其他視窗/分頁中登入帳戶的時間。
  • 指示 worker 執行部分背景工作
  • 瞭解服務何時執行了某些動作。
  • 使用者在一個視窗中上傳相片時,將相片傳遞到其他開啟的頁面。

範例 - 顯示使用者登出的網頁,包括同一個網站上另一個已開啟的分頁:

<button id="logout">Logout</button>

<script>
function doLogout() {
    // update the UI login state for this page.
}

const authChannel = new BroadcastChannel('auth');

const button = document.querySelector('#logout');
button.addEventListener('click', e => {
    // A channel won't broadcast to itself so we invoke doLogout()
    // manually on this page.
    doLogout();
    authChannel.postMessage({cmd: 'logout', user: 'Eric Bidelman'});
});

authChannel.onmessage = function(e) {
    if (e.data.cmd === 'logout') {
    doLogout();
    }
};
</script>

在另一個範例中,假設您想要指示 Service Worker 移除 使用者變更「離線儲存空間設定」後快取的內容。 您可以使用 window.caches 刪除其快取,但 Service Worker 可能會 已經包含執行此動作的公用程式。我們可以使用 Broadcast Channel API 可重複使用該程式碼!如果沒有 Broadcast Channel API,您就必須循環處理 self.clients.matchAll() 的結果並對每個用戶端呼叫 postMessage(),才能讓服務工作處理程序與所有用戶端進行通訊 (執行這項作業的實際程式碼)。使用廣播頻道會讓這部O(1),而不是 O(N)

範例 - 指示 Service Worker 移除快取,重複使用其內部公用程式方法。

在 index.html 中

const channel = new BroadcastChannel('app-channel');
channel.onmessage = function(e) {
    if (e.data.action === 'clearcache') {
    console.log('Cache removed:', e.data.removed);
    }
};

const messageChannel = new MessageChannel();

// Send the service worker a message to clear the cache.
// We can't use a BroadcastChannel for this because the
// service worker may need to be woken up. MessageChannels do that.
navigator.serviceWorker.controller.postMessage({
    action: 'clearcache',
    cacheName: 'v1-cache'
}, [messageChannel.port2]);

在 sw.js 中

function nukeCache(cacheName) {
    return caches.delete(cacheName).then(removed => {
    // ...do more stuff (internal) to this service worker...
    return removed;
    });
}

self.onmessage = function(e) {
    const action = e.data.action;
    const cacheName = e.data.cacheName;

    if (action === 'clearcache') {
    nukeCache(cacheName).then(removed => {
        // Send the main page a response via the BroadcastChannel API.
        // We could also use e.ports[0].postMessage(), but the benefit
        // of responding with the BroadcastChannel API is that other
        // subscribers may be listening.
        const channel = new BroadcastChannel('app-channel');
        channel.postMessage({action, removed});
    });
    }
};

postMessage()的差異

postMessage() 不同的是,您不再需要保留 iframe 或 worker 的參照,就能與 iframe 或 worker 通訊:

// Don't have to save references to window objects.
const popup = window.open('https://another-origin.com', ...);
popup.postMessage('Sup popup!', 'https://another-origin.com');

window.postMessage() 也可讓您跨來源進行通訊。Broadcast Channel API 與來源相同。由於訊息保證會來自相同來源,因此不必像我們習慣 window.postMessage() 一樣驗證訊息:

// Don't have to validate the origin of a message.
const iframe = document.querySelector('iframe');
iframe.contentWindow.onmessage = function(e) {
    if (e.origin !== 'https://expected-origin.com') {
    return;
    }
    e.source.postMessage('Ack!', e.origin);
};

只需「訂閱」以及安全雙向通訊!

與 SharedWorkers 的差異

如果需要將訊息傳送到多個視窗/分頁或工作站,請使用 BroadcastChannel 在簡單的情況下。

對於更複雜的使用情境,像是管理鎖定、共用狀態、在伺服器和多個用戶端之間同步處理資源,或是與遠端主機共用 WebSocket 連線,共用工作站會是最適當的解決方案。

與 MessageChannel API 的差異

Channel Messaging APIBroadcastChannel 的主要差異在於,後者是將訊息分派給多個事件監聽器 (一對多) 的方式。MessageChannel 適用於指令碼之間的一對一通訊,而且也需要設定頻道每一端的通訊埠。

功能偵測和瀏覽器支援

Chrome 54、Firefox 38 和 Opera 41 目前支援 Broadcast Channel API。

if ('BroadcastChannel' in self) {
    // BroadcastChannel API supported!
}

至於 polyfill 的例子,這裡分為:

我還沒試過這些方法,因此你的里程數可能會有所不同。

資源