Leonardo Campos
Leonardo Campos

Reputation: 46

communication between iframe using postMessage

I'm trying to remove buttons from a screen that I access with an iframe so that my parent software doesn't make changes through the buttons. To do this, I am using postMessage communication to inform a variable in the ifram's child application, but in this application the change to the variable that I send is not happening.

The code is javascript, so there is no debugging, so I am using consoleLogs to see what is coming to the console. And I haven't found the update yet.

FOR SENDING:

const sendBooleanToIframe = () => {
    const iframe = frameRef.current
    if (iframe) {
      setTimeout(() => {
        iframe.contentWindow?.postMessage({ yourBooleanVariable: true }, '*')
      }, 3000)
    }
}
useEffect(() => {
    const iframeLoadHandler = () => {
      sendBooleanToIframe()
    }
    const iframe = frameRef.current
    if (iframe) {
      iframe.addEventListener('load', iframeLoadHandler)
    }
    return () => {
      if (iframe) {
        iframe.removeEventListener('load', iframeLoadHandler)
      }
    }
}, [])

FOR RECEIVED:

setTimeout(() => {
 useEffect(() => {
  const handleMessage = (event) => {
    console.log('start handleMessage diagnostics')
   if (event.data.yourBooleanVariable) {
    console.log('Menssage iframe:', event.data.yourBooleanVariable)
    headerInfo = false
   }
  };
  window.addEventListener('message', handleMessage)
  return () => {
   window.removeEventListener('message', handleMessage)
  }
 }, [])
} , 3000)

Upvotes: 1

Views: 515

Answers (1)

David Bradshaw
David Bradshaw

Reputation: 13077

A few things.

First useEffect() can not be in a setTimeout function.

Second in React the event handlers should be added via the html in your function.

<iframe src=“” onload={sendBooleanToIframe} />

Third the receive function should be in your base app code, not inside a React function. It binds to window and needs to be set up in the first JS event loop on the page, as after this the onload event in the parent will fire. You don’t need to wait for React to render the rest of the page.

Forth you should not need any setTimeout() calls when using postMessage().

Fifth all the main browsers have JS debuggers in them. The best on is in Chrome.

Upvotes: 0

Related Questions