Javascript: Shared Worker

Broadcast message on all ports:

const ports = [];

self.onconnect = function(e) {
  const port = e.ports[0];
  ports.push(port);

  port.onmessage = function(e) {
    // When a message is received from any port, send it to all other connected ports
    for (let i = 0; i < ports.length; i++) {
      if (ports[i] !== port) { // Avoid sending the message back to the sender
        ports[i].postMessage(e.data);
      }
    }
  };

  // Start the port to receive messages
  port.start();

  // Handle disconnection
  port.onclose = function() {
    ports = ports.filter(p => p !== port);
  };
};

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *