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.
// 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
Syntax
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.originagainst an exact allow-list before usingevent.data, and compare with===, neverstartsWith()orincludes(). Also check thesourceif 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
dataas untrusted input. Validate its shape. Never put it intoinnerHTMLoreval(). - 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)andworker.onmessage; inside the worker,self.onmessageandself.postMessage(). Settingonmessageon aMessagePortstarts it automatically, whileaddEventListener("message", ...)needsport.start(). messageerrorfires when a message arrives that cannot be deserialized.- Same-origin tabs. For tabs of one site,
BroadcastChannelis simpler than keeping window references. - Large data. Transfer an
ArrayBufferinstead 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.
Related
structuredClone()โ the same copying algorithmwindow.open()addEventListener()CustomEventโ events inside one page- Lessons: Events, Security