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
- Check
event.originagainst an explicit allowlist before doing anything. - Validate the message
datashape; neverevalit or treat it as trusted HTML. - When you send, pass a specific
targetOrigininstead of'*'.
window.addEventListener('message', (e) => {
if (e.origin !== 'https://trusted.example') return;
// safe to handle e.data
});
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
- Subdomain takeover: a dangling DNS record an attacker can claim
- Debug artifacts, risky TODOs, and leaked AI prompts in your build
- TLS and email checks: weak HTTPS and a spoofable domain
- Sensitive data shipped to the browser: config, internal fields, and bulk PII