iframe之间使用postMessage通信

问题描述 投票:0回答:1

我正在尝试从使用 iframe 访问的屏幕上删除按钮,以便我的父软件不会通过按钮进行更改。为此,我使用 postMessage 通信来通知 iram 子应用程序中的变量,但在此应用程序中,我发送的变量没有发生更改。

代码是javascript,所以没有调试,所以我使用consoleLogs来查看控制台中出现了什么。而且我还没有找到更新。

发送:

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)
      }
    }
}, [])

对于已收到:

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)
javascript iframe postmessage
1个回答
0
投票

一些事情。

首先

useEffect()
不能在setTimeout函数中。

React 中的第二个事件处理程序应该通过函数中的 html 添加。

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

第三,接收函数应该位于您的基本应用程序代码中,而不是位于 React 函数内。它绑定到

window
并且需要在页面上的第一个 JS 事件循环中设置,因为在此之后父级中的
onload
事件将触发。您不需要等待 React 渲染页面的其余部分。

第四,使用

setTimeouts()
时,您不需要任何
postMessage()

© www.soinside.com 2019 - 2024. All rights reserved.