Browser multi-page communication Broadcast Channel and SharedWorker

In daily development, we may encounter a requirement that requires us to perform certain operations on a certain page, and simultaneously operate to another page, such as visiting a music website, opening a new page to listen to a certain music, and then returning to the When switching to other songs on the original page, the music playing page should also switch to the corresponding song synchronously.

Broadcast Channel API

The Broadcast Channel API enables message communication between different browser tabs. Through the Broadcast Channel API, you can create a channel (channel), and send and receive messages in different tabs.

Send a message

const channel = new BroadcastChannel('myChannel'); 
channel.postMessage({
    
     message: 'Hello' })

receive message

const channel = new BroadcastChannel('myChannel');
channel.addEventListener('message', function(event) {
    
    
    const receivedData = event.data;
    // 处理接收到的数据
    console.log(receivedData);
});

close connection

channel.close();

SharedWorker

SharedWorker is a background thread that shares the execution environment between different tab pages, enabling communication between multiple tab pages. Different tabs can send and receive messages through SharedWorker. The worker js of the same url will only create a sharedWorker, and other pages will use the same url to create a sharedWorker, and the created worker will be reused. This worker is shared by those pages.

// worker.js
var clients = [];
onconnect = function(e) {
    
    
  var port = e.ports[0];
  clients.push(port);
  port.addEventListener("message", function(e) {
    
    
    for (var i = 0; i < clients.length; i++) {
    
    
      var eElement = clients[i];
      eElement.postMessage(e.data);
    }
  });
  port.start();
};

Send a message

const worker = new SharedWorker('worker.js'); 
worker.port.postMessage({
    
     message: 'Hello' });

receive message

const worker = new SharedWorker('worker.js');
worker.port.addEventListener('message', function(event) {
    
    
    const receivedData = event.data;
    // 处理接收到的数据
    console.log(receivedData);
});

It should be noted that in the case of cross-domain, it may be necessary to use other technical means, such as WebSocket, server-side message push, etc.

The difference between BroadcastChannel and SharedWorker:

  • Communication scope: BroadcastChannel can communicate messages between different tabs in the same browser, while SharedWorker can share the execution environment between different tabs, and can also communicate in different windows or browsers.
  • Data broadcasting: BroadcastChannel can only broadcast messages between tabs in the same browser, while SharedWorker can deliver messages to all windows or tabs connected to the same SharedWorker.
  • Shared data: SharedWorker allows data to be shared between each connected tab. Tabs can share the same state, variable or object through SharedWorker, which can be used to share state or implement shared functionality. The BroadcastChannel is only used to transmit simple messages, and does not have the ability to share data.
  • Life cycle: SharedWorker is a thread that runs in the background and will continue to exist when there are no connected tabs, while BroadcastChannel is only valid when there are connected tabs.

Therefore, BroadcastChannel is more suitable for simple message communication between different tabs of the same browser, while SharedWorker is more suitable for sharing state, data and functions, and can realize more complex cross-tab or cross-window communication requirements.

Guess you like

Origin blog.csdn.net/weixin_43589827/article/details/132337794