Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Transferring an ArrayBuffer with postMessage: ownership and detachment

Transferring an `ArrayBuffer` with `postMessage()` detaches the sender’s buffer before delivery. Without a transfer list, the bytes are copied.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

worker.postMessage(message)
worker.postMessage(message, [buffer])
worker.postMessage(message, { transfer: [buffer] })
self.postMessage(message, [buffer]) // Dedicated worker global scope
port.postMessage(message, [buffer])
port.postMessage(message, { transfer: [buffer] })
targetWindow.postMessage(message, targetOrigin, [buffer])
targetWindow.postMessage(message, { targetOrigin, transfer: [buffer] })

When an ordinary ArrayBuffer is in the message but not on the transfer list, structured cloning copies its bytes and leaves the sender’s buffer usable. Listing the buffer transfers ownership of its backing memory instead of sharing it. On a successful transfer, the sender’s buffer is already detached when the call returns. If the message arrives, the receiver gets a new buffer object with the original bytes in event.data at a later message event. Detachment does not confirm delivery.

Put the same buffer in the message, such as { buffer }, and on the transfer list [buffer]. Listing it alone can detach it without exposing it in the message data. A Uint8Array or DataView can be cloned but cannot itself go on the transfer list. Use view.buffer: this transfers the whole backing buffer, not just the view’s range.

Detachment does not delete the object or its references. buffer.byteLength and the byteLength of existing typed arrays backed by it return 0, but reading byteLength on a DataView backed by it throws TypeError. A length of 0 alone does not prove detachment: an attached buffer can be empty. Where the ECMAScript 2024 getter ArrayBuffer.prototype.detached is supported, check buffer.detached.

A duplicate buffer, an already detached buffer, a view or SharedArrayBuffer on the transfer list, or an uncloneable message value such as a function can cause a synchronous DataCloneError DOMException. A SharedArrayBuffer, where sending it is permitted, shares memory rather than transferring ownership.

Worker, MessagePort, and the dedicated worker global scope accept a list or { transfer } options after the message. For a window, use a separate targetOrigin before the list or use { targetOrigin, transfer }. The default "/" means the sender’s origin. Specify an exact target origin instead of "*" when known; on receipt, check event.origin, check event.source where relevant, and validate the data. postMessage() is a web platform API, not part of ECMAScript; runtime support varies.

Examples

(() => {
  const { port1, port2 } = new MessageChannel();
  const view = new Uint8Array([7, 42, 255]);
  const buffer = view.buffer;

  port2.onmessage = ({ data }) => {
    const bytes = new Uint8Array(data.buffer);
    console.log(`received: ${bytes.byteLength} bytes (${bytes.join(', ')})`);
    port1.close();
    port2.close();
  };

  console.log(`before: buffer=${buffer.byteLength}, view=${view.byteLength}`);
  port1.postMessage({ buffer }, [buffer]);
  console.log(`after: buffer=${buffer.byteLength}, view=${view.byteLength}`);
})();

Result

before: buffer=3, view=3
after: buffer=0, view=0
received: 3 bytes (7, 42, 255)

Run in a browser developer console. Both ports operate on the same page, without a worker. Expect the two sender lines first, then the receiver line with the three unchanged bytes.

Related lessons

  • JavaScript · Lesson 5 · Advanced · Version: 4

Sources