← Back to Frontend, page 2

frontend-0037 · Medium mid

How do you use postMessage between a page and an iframe safely?

Send with an explicit target origin and never with the wildcard for private data. When receiving, check event.origin against an allowlist, and validate the shape and size of event.data before using it, because any window can send a message to your page.

Full answer

window.postMessage(data, targetOrigin) is the supported way for windows from different origins to talk, for example a page and an embedded payment or video widget. It works because the browser sends the message with the true origin of the sender, and the receiver can look at it.

Two sides, two rules.

Sending:

  • Always pass the exact targetOrigin, such as 'https://widgets.example.com'. The browser delivers the message only if the receiving window is on that origin. With '*', the message goes to whatever page is in the frame at that moment, which may have been navigated to an attacker's site.
  • Do not send secrets unless the target origin is exact.

Receiving:

  • Listen with window.addEventListener('message', handler). Any window that has a reference to yours can send a message, including a malicious one that embedded you or opened you.
  • Check event.origin against an allowlist with strict equality. Do not use includes or endsWith, because https://app.schoolabe.com.evil.example passes an includes check.
  • Check event.source when you expect a particular window.
  • Validate event.data: the type, the allowed fields and the size. Treat it as untrusted input, and never put it into innerHTML or eval.
  • Ignore messages that are not for you, because libraries and browser extensions also post messages.

Message passing with structured clone allows many types, but not functions. Use a small protocol with a type field and handle each type explicitly.

The snippet is a receiver with an allowlist. In the test, a parent page on one origin and a second page on another origin both embed the same child frame and post a resize message. The child accepts the trusted parent and ignores the other. The test replaced the trusted origin placeholder with the real test origin.

javascript
const TRUSTED = 'https://app.schoolabe.com';
window.accepted = 0;

window.addEventListener('message', (event) => {
  if (event.origin !== TRUSTED) return;                  // exact match only
  const data = event.data;
  if (!data || data.type !== 'resize') return;           // our own small protocol
  const height = Number(data.height);
  if (!Number.isFinite(height) || height < 0 || height > 2000) return;
  document.body.style.height = `${height}px`;
  window.accepted += 1;
});

// Sending side, in the parent page:
// frame.contentWindow.postMessage({ type: 'resize', height: 300 }, 'https://widgets.example.com');

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. A child frame on 127.0.0.1 was embedded by two parent pages on different localhost ports, with the first one trusted. The trusted parent's message was accepted, and the other parent's message was ignored. The test replaced the placeholder origin with the real test origin.

Key points

  • postMessage is the safe cross-origin channel, with the real origin attached.
  • Send with an exact target origin, never * for private data.
  • Receive with a strict equality check on event.origin.
  • Validate type, shape and size of the data.
  • Never put message data into innerHTML or eval.

Common mistakes

  • Checking origin with includes or endsWith.
  • Using * as the target origin for sensitive data.
  • Trusting event.data without validation.
  • Forgetting to ignore messages that are not part of your protocol.

Follow-ups

  • What does event.source give you?
  • How would you reply to the sender safely?
  • How does this compare to a MessageChannel?

Tips

  • Explain both directions: target origin on send, event.origin on receive.
  • Give the includes bypass as the common error.