Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท DOM: Events

The message event and postMessage()

Reference for the message event and postMessage(): send data between windows, iframes, workers and MessageChannel ports, and verify event.origin and event.source.

The message event delivers data sent with postMessage(). It is the safe, standard way for two separate browsing contexts to talk: a page and an <iframe>, a page and a popup window, a page and a Web Worker, or two MessagePorts. The sender and receiver may even be on different origins; the browser copies the data between them with the structured clone algorithm, so no objects are shared.

Messaging is built on the idea that the receiver decides whether to trust the sender. Always check where a message came from before acting on it.

JavaScript
// sender
otherWindow.postMessage({ type: "ping" }, "https://example.com");

// receiver
window.addEventListener("message", (event) => {
  if (event.origin !== "https://app.example.com") return; // ignore strangers
  console.log(event.data);
});

Try it

A page talking to an iframe
MessageChannel: two connected ports

Syntax

JavaScript
targetWindow.postMessage(message, targetOrigin)
targetWindow.postMessage(message, { targetOrigin, transfer })
worker.postMessage(message, transfer)
port.postMessage(message, transfer)

target.addEventListener("message", (event) => { /* ... */ });

Parameters

Name Description
message Any structuredCloneable value: strings, numbers, plain objects, arrays, Map, Set, Date, ArrayBuffer and more. Functions and DOM nodes cannot be cloned and throw a DataCloneError.
targetOrigin For window.postMessage(): the origin the receiver must have, such as "https://example.com". "/" means the same origin as the sender, and "*" means any origin.
transfer Optional array of transferable objects (for example ArrayBuffer, MessagePort) whose ownership moves to the receiver.

The MessageEvent object

Property Description
data The received value (a clone).
origin The sender's origin, as a string. "null" (the text) for an opaque origin such as a sandboxed frame.
source The sender's Window (for window messages); null for workers and ports.
ports Array of MessagePorts that were transferred with the message.

Usage notes

  • Check event.origin against an exact allow-list before using event.data, and compare with ===, never startsWith() or includes(). Also check the source if you only expect one window.
  • Name the target origin. postMessage(data, "*") hands the data to whatever page is currently loaded in that window. Use "*" only for non-sensitive data or opaque-origin frames.
  • Treat data as untrusted input. Validate its shape. Never put it into innerHTML or eval().
  • It is asynchronous. The handler runs later, as a separate task, never inside postMessage().
  • Workers use the same pattern. In a page, worker.postMessage(data) and worker.onmessage; inside the worker, self.onmessage and self.postMessage(). Setting onmessage on a MessagePort starts it automatically, while addEventListener("message", ...) needs port.start().
  • messageerror fires when a message arrives that cannot be deserialized.
  • Same-origin tabs. For tabs of one site, BroadcastChannel is simpler than keeping window references.
  • Large data. Transfer an ArrayBuffer instead of copying it when you do not need it afterwards: postMessage(buffer, [buffer]).

Browser support

postMessage() and the message event for windows, workers, MessageChannel and BroadcastChannel work in every current browser.