iframe通信 postmessage(低代码)

125 阅读1分钟
// 父页面和子页面通信
// A.html (父)
<iframe src="./B.html" frameborder="1" id="Bframe"></iframe>
const msg = {
    name: "Fhup"
  }
window.onload = () => {
  // 自动调用必须放在onload中,通过事件调用则不用
  // let frame = document.querySelector("#Bframe").contentWindow
  let frame = window.frames[0]
  frame.postMessage(msg, "http://127.0.0.1:5501/demo.html")
}

// B.html
window.addEventListener("message", (e) => {
  console.log(e.data)
  console.log(e.origin)
  console.log(e.source)
})

// 子页面和父页面通信
// A.html (父)
<iframe src="./B.html" frameborder="1" id="Bframe"></iframe>
window.addEventListener("message", (e) => {
  console.log(e.data)
  console.log(e.origin)
  console.log(e.source)
})

// B.html
const msg = {
  name: "Fhup"
}
window.top.postMessage(msg, "http://127.0.0.1:5501/demo.html")

image.png

在react中进行iframe通信

从低代码到iframe

  const iFrame = document.getElementById('previewIframe') as HTMLIFrameElement;
  useEffect(() => {
    // 初始化获取数据并同步数据
    if (iFrame && iFrame.contentWindow) {
      setTimeout(() => {
        iFrame.contentWindow!.postMessage(shopSchema?.schema, 'http://localhost:3007/#/preview');
      }, 1000)
    }
  }, [])
  //监听传过来的postmessage数据
  useEffect(() => {
    window.addEventListener('message', (e) => {
      if (e.origin === 'http://localhost:3000') {
        e.data && setXXX(e.data)
      }
    });
  }, []);

从iframe发送数据到低代码

  useUpdateEffect(() => {
    window.parent.postMessage({ xxx1: info1, xxx2: info2 }, "*");
  }, [])
  // 低代码端接收数据
  useEffect(() => {
    window.addEventListener('message', ({ data }) => {
      const { xxx1, xxx2 } = data;
      setXXX(xxx1);
    });
  }, []);