← Learn

Unvalidated postMessage: a cross-window message handler without an origin check

A window.addEventListener("message") handler that does not check event.origin can let any site send your app commands. Here is the one-line fix.

window.postMessage lets different windows or iframes talk to each other. The danger is on the receiving end: a handler that acts on messages without checking who sent them will trust a message from any website that can open or embed your page.

The risk

If your handler updates state, navigates, or calls an API based on message data, an attacker's page can drive that behavior — a path to XSS, auth bypass, or data theft.

The fix

  1. Check event.origin against an explicit allowlist before doing anything.
  2. Validate the message data shape; never eval it or treat it as trusted HTML.
  3. When you send, pass a specific targetOrigin instead of '*'.
window.addEventListener('message', (e) => {
  if (e.origin !== 'https://trusted.example') return;
  // safe to handle e.data
});

→ Scan your app free

FAQ

Why is a postMessage handler without an origin check dangerous?
Because any site that can open or embed your page can send messages your handler will act on, potentially driving navigation, state changes, or API calls on the user’s behalf.

What is the fix?
Check event.origin against an allowlist before handling the message, validate the data shape, and send with a specific targetOrigin instead of “*”.

Related questions

Check your own app
Free passive scan, ~10 seconds, no login.