← Lessons

quiz vs the machine

Gold1440

Frontend

PostMessage Security

How to exchange data between windows safely by validating origin and never trusting incoming messages.

5 min read · core · beat Gold to climb

What it is

postMessage lets two browsing contexts such as a page and an iframe send data across origins. It is powerful but a common source of bugs when origins are not checked.

The two mistakes

  • Sending to a wildcard target origin leaks data to any page that happens to be loaded in the frame.
  • Trusting the received message without checking its origin lets any site send you commands.

Safe pattern

  • When sending, pass the exact target origin instead of a wildcard star.
  • When receiving, verify event origin against an allowlist before acting.
  • Validate the shape and type of the message data, treating it as untrusted input.

Why both sides matter

Origin can be spoofed only by the browser if you skip the check; the browser sets event origin honestly, so verifying it is reliable. But you must actually read it.

Key idea

postMessage is safe only when you send to an exact origin and verify event origin and data shape on receipt.

Check yourself

Answer to earn rating on the learn ladder.

1. What should you check on a received postMessage?

2. Why avoid a wildcard target origin when sending?