Communicating between Web Workers via MessageChannel
Occasionally, you want Web Workers to communicate with each other. Doing so is not obvious as most Web Worker examples are about communicating between the main thread and a Web Worker. There, one uses postMessage() to send messages directly to the Worker. Alas, that doesn’t work for communicating between two Workers, because you can’t pass references to Workers around. MessageChannel The solution is to establish a channel between the Workers: const channel = new MessageChannel(); receivingWorker.postMessage({port: channel.port1}, [channel.port1]); sendingWorker.postMessage({port: channel.port2}, [channel.port2]); We are creating a new MessageChannel and sending references to its two ports to two Workers. Every port can both send and receive messages. Note the second parameter of postMessage() : It specifies that channel.port1 and channel.port2 should be transfered (not copied) to the Workers. We can do that because MessagePort implements the interface Transferable . Po...