Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript postMessage not working in a ReactJS app with iframes

I have two separated ReactJS apps running on port 3000 and 3001. The main app has an iframe to render the other app. Working fine so far. The problem rise up when trying to send data from main app to the other app using postMessage.

This is what I have:

    export default function RenderIframe({src, width, height}: IframeProps) {
  const iRef = useRef<HTMLIFrameElement | null>(null);

  const handleLoad = () => {
    iRef.current.contentWindow.postMessage('hello', '*');
  }

  return (
    <Box>
      <iframe src={src} width={width} height={height} ref={iRef} onLoad={handleLoad} />
    </Box>
  );
}

and in the other app I have:

 useEffect(() => {
      window.addEventListener("message", (e: MessageEvent) => {
        console.log(e.data);
      });
    }
  }, []);

But instead of "hello" I get nothing. What am I missing here?

like image 444
assembler Avatar asked Sep 05 '25 01:09

assembler


1 Answers

Responding my own question, but credit goes to @Konrad. Despite the app waits for the iframe's onload event it also needs to wait a little longer, just 100 (maybe less) milliseconds more, so the solution is this:

const handleLoad = () => {
   setTimeout(() => {  
    iRef.current.contentWindow.postMessage('hello', '*');
   }, [100]);
}
like image 143
assembler Avatar answered Sep 07 '25 13:09

assembler