window.postMessage between a React page and an iframe does nothing
postMessage runs without an error but the other window never logs anythingShort answer
postMessage fails silently. A message is dropped when targetOrigin does not match the receiver's exact origin, when the iframe has not loaded yet, or when no message listener is attached on the receiving side. Log origin on both sides, wait for load, and register the listener inside useEffect with cleanup.
Fix it fast
1Find out which cause you have
Log on both sides to see which half is silent. Sender logs where it posts; receiver logs every message.
// sender console.log("posting to", targetOrigin, iframeRef.current?.contentWindow); // receiver window.addEventListener("message", (e) => console.log(e.origin, e.data));2Match what you see, then jump to its fix
- 1
No error, and nothing arrives; works once you test with * onlytargetOrigin does not match the receiver's originFix - 2
iframe.contentWindow is null, or the message is posted in the first effect and never arrivesThe message is sent before the iframe has loadedFix - 3
Receiver code never logs; or it logs but ignores the dataThe receiving listener is missing, filtered out, or removedFix
- 1
What does the error look like?
postMessage runs without an error but the other window never logs anythingiframe.contentWindow is nullThe message works on localhost but not in production
Cause 1 of 3
targetOrigin does not match the receiver's origin
1Check
MDN says the origin must match exactly, including scheme, hostname and port, and a mismatch means the message is silently not delivered. A redirect to another host also changes it.
console.log(iframeRef.current?.src, window.location.origin)2Fix
Pass the exact origin of the iframe's document, not the parent's, and not a path.
iframeRef.current.contentWindow.postMessage(
{ type: "ping" },
"https://widget.example.com"
);3Verify
The receiver's log line shows the message with the expected origin.
// browser console of the iframe: look for the logged origin and dataConfirmed by developer.mozilla.org
Cause 2 of 3
The message is sent before the iframe has loaded
1Check
MDN lists a target that is not ready, or whose listener is not registered yet, as a reason for a message not arriving, and says to use iframe.contentWindow after the iframe has loaded.
console.log("ready?", document.readyState, iframeRef.current?.contentWindow)2Fix
Send from the iframe's onLoad handler, or have the iframe post a hello message first and reply to event.source.
<iframe
ref={iframeRef}
src="https://widget.example.com/embed"
onLoad={() =>
iframeRef.current?.contentWindow?.postMessage(
{ type: "init" },
"https://widget.example.com"
)
}
/>3Verify
The init message reaches the iframe once per page load.
// receiver console shows one init messageConfirmed by developer.mozilla.org
Cause 3 of 3
The receiving listener is missing, filtered out, or removed
1Check
A listener inside a component must be added in an Effect and removed in the returned cleanup, using the same function reference. MDN also says to check event.origin before trusting the data, so a guard that rejects the real origin looks like a lost message.
grep -rn "addEventListener(\"message\"\|addEventListener('message'" src/2Fix
Register once in useEffect, check the sender's origin against the exact expected value, then act on the data.
useEffect(() => {
function onMessage(event) {
if (event.origin !== "https://widget.example.com") return;
setReply(event.data);
}
window.addEventListener("message", onMessage);
return () => window.removeEventListener("message", onMessage);
}, []);3Verify
Send a message and see the state update. Unmounting the component removes the listener.
// React DevTools: the component state shows the replyConfirmed by react.dev
How do I stop it coming back?
- Never use * for sensitive data; MDN says to always give a specific targetOrigin when you know it.
- Keep the allowed origins in one constant used by both the send and receive code.
- Log origin and data while debugging, and remove the logs afterwards.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- TaskvareA task and project-management suite: React on the web, Flutter on mobile, TypeScript underneath.
Related fixes
Web apps
Module not found for antd/dist/antd.less after upgrading to Ant Design 5
Module not found: Error: Can't resolve 'antd/dist/antd.less'
Ant Design 5 dropped Less and the bundled CSS file for CSS-in-JS, so antd/dist/antd.less no longer exists.
3 causes, each with a fixWeb apps
Astro Code component fails inside a React component
Astro components cannot be rendered directly via function call
Astro components such as Code only exist on the server and render static HTML.
2 causes, each with a fixWeb apps
React shows Attempted import error when importing a component or function
Attempted import error:
The build found the file but not the name you asked for.
2 causes, each with a fixWeb apps
How to catch and handle a 422 from Axios in a Redux thunk
action.error.message is 'Rejected' and action.payload is undefined
A 422 means the server read the request but cannot process its content, so repeating it unchanged fails again.
4 causes, each with a fixWeb apps
axios gets 429 Too Many Requests from a React app
429 (Too Many Requests)
A 429 comes from the server or an API gateway, not from axios: your client sent too many requests in a window.
4 causes, each with a fixWeb apps
Axios request is not cancelled when a React component unmounts
A cancelled request is logged as an error in the catch block
Axios cancels a request when you pass it an AbortSignal and later call abort() on its controller.
4 causes, each with a fix