How to send transferrable object from web worker to parent in javascript?

301 views Asked by At

In JS, I made a web worker, and want to send a transferable object back to parent.

In the web worker, I have

var NUMS = new ArrayBuffer(3);
NUMS[0] = 10;
NUMS[1] = 11;
NUMS[2] = 12;
postMessage(NUMS, [NUMS]);

Then in the main thread, I have

worker.onmessage = function(e) {
    var first = e.data[0]; // undefined but the bytelength is 3
}

but what happens is all the values of the array buffer seems to be cleared or invalid. Does anyone know how to fix this?

1

There are 1 answers

0
omega On

Turns out you need to use one of the typed arrays

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays

var NUMS = new Int16Array(3);
NUMS[0] = 10;
NUMS[1] = 11;
NUMS[2] = 12;
postMessage(NUMS.buffer, [NUMS.buffer]);

then you can get it by

worker.onmessage = function(e) {
    var a = new Int16Array(e.data);
    var first = a[0]; 
}