Transfer ArrayBuffer from main.js to worker.js work as expected:
after sending ArrayBuffer is no longer usable in main.js.
// main.js
const array = new Uint32Array(1_000_000).map((v, i) => i);
console.log(array.byteLength); // 4000000
const worker = new Worker(new URL('worker.js', import.meta.url), { type: 'module' });
worker.postMessage(array, [array.buffer]);
console.log(array.byteLength); // 0 <= GOOD, as expected
But transferring ArrayBuffer from worker.js to main.js doesn’t work as expected:
after sending ArrayBuffer is still usable in worker.js.
// worker.js
onmessage = function handleMessageFromMain(msg) {
const array = new Uint32Array(1_000_000).map((v, i) => i);
console.log(array.byteLength); // 4000000
postMessage(array, null, [array.buffer]);
console.log(array.byteLength); // 4000000 <= BAD, must be 0
};
How to transfer ArrayBuffer from worker to main?