Catalog My learning Blog
Browser Security Headers: CORS, CSP and Cookies Explained · Phase 1 · Lesson 5 · 6 min read

postMessage Security: Cross-Origin Messaging

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: A Correct Sender and Receiver Pair
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Use window.postMessage correctly for cross-origin communication, including specifying an exact targetOrigin rather than a wildcard and validating event.origin on receipt, and explain why omitting either check converts the channel into a vulnerability.

Concept Explanation

postMessage is the web platform's sanctioned channel between browsing contexts that do not share an origin: a page and an iframe it embeds, a page and a popup it opened, or a page and its opener. It is deliberately minimal. One side calls targetWindow.postMessage(data, targetOrigin) and the other side receives a message event carrying the data plus metadata about where it came from. Nothing else is shared: no DOM access, no variables, no functions, only structured-cloneable data crossing an explicit boundary.

The security of the channel rests entirely on two checks, one on each end, and both are optional in the API, which is precisely why they are so often missing. On the sending side, the second argument targetOrigin tells the browser which origin the receiving document must currently be for the message to be delivered at all. Passing the literal string asterisk disables that check, meaning the message is delivered wherever that window happens to have navigated to. If the data contains a session token, a user identifier, an OAuth code, or anything else sensitive, a wildcard targetOrigin hands it to whatever origin now occupies that window, which an attacker who controls any part of the navigation can influence.

On the receiving side, the message event carries an origin property containing the serialized origin of the sending document. Any window on the internet can call postMessage on any window it has a reference to, which includes a page that framed you, a page you opened, and a page that opened you. Without an event.origin check your handler processes messages from arbitrary attacker pages as though they came from your own partner, and whatever your handler does with that data, writing it into innerHTML, storing a token, initiating a transaction, becomes something an attacker can trigger at will.

The origin check must also be an exact comparison, not a substring test. A check written as a call to indexOf or includes against the string trusted.example passes for https://trusted.example.evil.com and for https://nottrusted.example. A check using a regular expression with an unescaped dot passes for trustedxexample.com. A check that only compares the hostname ignores the scheme and would accept an HTTP origin for an HTTPS partner. The correct form is a strict equality comparison against a hardcoded expected origin string, or membership in a small allowlist Set of exact origin strings.

Two further points matter in practice. First, treat the message payload as untrusted input even after the origin check passes, because the sending origin may itself have an XSS flaw, so validate the message shape and type before acting on it and never pass it to innerHTML or eval. Second, prefer MessageChannel for long-lived conversations: the two sides exchange a port once, after an origin-validated handshake, and subsequent messages travel over a private channel that third parties have no reference to at all, which removes the need to re-validate origin on every message.

MistakeCode shapeConsequence
Wildcard targetOriginpostMessage(token, '*')The payload is delivered to whatever origin now occupies the target window
No origin check on receiptonmessage = e => render(e.data)Any page on the internet can drive your handler with arbitrary data
Substring origin checkif (e.origin.includes('trusted.example'))Matches https://trusted.example.evil.com and similar lookalikes
Origin check but unsafe sinkel.innerHTML = e.data.htmlAn XSS in the trusted partner origin becomes an XSS in yours

Worked Example: A Correct Sender and Receiver Pair

The contrast below is the entire lesson in twenty lines. Note that the fixed receiver validates the origin with strict equality, validates the message shape, and writes to textContent rather than innerHTML, so it is defended at three independent layers.

JavaScript
// VULNERABLE sender: delivered to whatever origin occupies that window now
widgetFrame.contentWindow.postMessage({ sessionToken: token }, '*');

// VULNERABLE receiver: no origin check at all, and an HTML sink
window.addEventListener('message', (e) => {
  document.getElementById('out').innerHTML = e.data.html;
});

// ------------------------------------------------------------------

// FIXED sender: an exact expected origin, so the browser silently drops
// the message if that window is no longer the widget
const WIDGET_ORIGIN = 'https://widget.example.com';
widgetFrame.contentWindow.postMessage({ type: 'init', userId }, WIDGET_ORIGIN);

// FIXED receiver: exact origin equality, shape validation, safe sink
const ALLOWED = new Set(['https://widget.example.com']);
window.addEventListener('message', (e) => {
  if (!ALLOWED.has(e.origin)) return;                 // exact match, not includes()
  const msg = e.data;
  if (!msg || msg.type !== 'widget:resize') return;   // validate the shape
  if (typeof msg.height !== 'number') return;         // validate the types
  widgetFrame.style.height = Math.min(msg.height, 2000) + 'px';
});
A postMessage exchange between two origins with the two mandatory checks marked: targetOrigin verified by the browser before delivery, and event.origin verified by the receiving handler before the payload is trusted.
A postMessage exchange between two origins with the two mandatory checks marked: targetOrigin verified by the browser before delivery, and event.origin verified by the receiving handler before the payload is trusted.

Real-World Examples

  • Security researcher Frans Rosen of Detectify published extensive research on postMessage vulnerabilities across major web properties, demonstrating repeatedly that handlers registered without an event.origin check could be driven by any attacker page that framed or opened the target, and releasing tooling to enumerate registered message handlers precisely because the pattern was so widespread across production sites.
  • OAuth 2.0 popup flows are a recurring source of this bug class: implementations that return an authorization code or access token to the opener with a wildcard targetOrigin hand that credential to whatever origin currently occupies the opener window, which is why the OAuth 2.0 for Browser-Based Apps guidance and major identity providers explicitly require an exact target origin when relaying a response through postMessage.
Common PitfallNever pass the wildcard as targetOrigin when the payload contains anything sensitive, and never register a message handler without a strict equality check on event.origin against a hardcoded allowlist. Substring and regular expression origin checks are the single most common way this defense is written incorrectly, because https://trusted.example.evil.com contains the string trusted.example.

Review Questions & Answers

It instructs the browser to deliver the message only if the receiving document's current origin matches the value given. The browser performs this check at delivery time, after the target window may have navigated. The wildcard disables the check entirely, so if the target window has been navigated to an attacker-controlled origin, whether through a redirect, an open redirect on the partner site, or simply the user following a link, the payload is delivered to the attacker instead of the intended recipient.

Substring matching accepts any origin that merely contains the expected string. The origin https://trusted.example.evil.com contains trusted.example, as does https://nottrusted.example, so both pass a substring check while being entirely attacker-controlled. The correct form is strict equality against a hardcoded full origin string including the scheme, or membership in a Set of such strings, because the serialized origin is a canonical value that can be compared exactly.

Because the origin check tells you which document sent the message, not that the document is behaving correctly. If the partner origin has an XSS vulnerability, an attacker running script there sends messages that pass your origin check perfectly. Validating the message type and field types, and using safe sinks such as textContent rather than innerHTML, means a compromise of the partner cannot immediately become a compromise of your page as well.

With MessageChannel the two sides perform one origin-validated handshake and then exchange a pair of ports. Subsequent messages travel over those ports, which no third party holds a reference to, so there is no window for an unrelated page to inject a message into the conversation and no need to repeat the origin check on every message. It narrows the exposed surface from "any window that can reach us" to "the specific counterpart we handed a port to."