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.