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;
}