Use transferable objects with a shared worker

1.1k Views Asked by At

When using transferable objects in my shared workers I receive null for event.data in the main thread. After some searching I found this post where is explained that the ArrayBuffer is always lost when it is passed through a MessagePort of a MessageChannel.

Shared worker communication is also done using ports and message channels. Does this mean that there is no way to use transferable objects in a SharedWorker instance? Or is there some workaround?

I need to transfer a huge string from SharedWorkerGlobalScope back to the main thread. The idea is to convert it to an ArrayBuffer as shown in this example and then transfer the buffer. This is supposedly much faster then sending the string...

Sending the data:

var arrayBuffer = convertStringToArrayBuffer( string );

var data = {
    message: "here is an array buffer",
    arrayBuffer: arrayBuffer 
};

port.postMessage(data, [data.arrayBuffer]);

receiving the data:

worker.port.onmessage = function( event ) {

    // data is null
    var data = event.data;

}
1

There are 1 best solutions below

6
On

Just use postMessage without transferables. Strings are not transferable anyway (so it is always copied).

The goal of having transferables is to have a minimal cost when passing objects from the sender to the receiver. Such messages can cross process boundaries, and doing inter-process communication is expensive. This is the reason why transferables are not supported yet with MessagePort. Incidentally, difficulty in cross-process communication is also the reason why Safari dropped support for SharedWorkers.