Is it possible to send messages from one WebWorker to another WebWorker?

I have a page where I intend to use a set of WebWorkers to perform background tasks. Each WebWorker has a specific function, but potentially useful to others. It is simple to receive / send messages from / to a WebWorker created by the page (or created by a specific WebWorker, in the case of subworkers), since there is a reference to the Worker in which one can add listeners or call methods:

var worker1 = new Worker("script1.js");
worker1.postMessage("bla");
worker1.onmessage = function(mensagem) {
    alert(mensagem.data);
};

var worker2 = new Worker("script2.js");
...

But if, say, the script1.js want to send a message to worker2, is it possible to do so without "routing" the message through the main thread? (i.e. onmessage of worker1 receives the message and does a postMessage pro worker2)

The reason is performance: like HTML5 Web Messaging serializes message parameters (and at the time of this writing most browsers do not yet support Transferables), this "routing" would require the data to be serialized and de-serialized twice, still that the overhead of sending two messages was negligible (which is not always true, since certain applications - WebGL for example - can keep the main thread busy for too long).

Author: mgibsonbr, 2013-12-11

1 answers

You can try using the MessageChannel to communicate between the two WebWokers . I'm working on a sample code in JsFiddle , but you can see something functional in these links:

 4
Author: Alexandre Marcondes, 2017-05-23 12:37:30