【问题标题】:window.onmessage not working in react js componentwindow.onmessage 在反应 js 组件中不起作用
【发布时间】:2021-06-27 10:47:06
【问题描述】:

我必须在 iframe 中加载 react js 应用程序,并且父应用程序正在使用以下代码向 iframe 反应应用程序发送数据:

  const myiframe = document.getElementById('myIframe');
  myiframe.contentWindow.postMessage('message', '*');


  <iframe id='myIframe' name="my-iframe" src="http://localhost:3000" ></iframe>

在 iframe 应用中,我正在尝试接收数据:

useEffect(() => {
    window.onmessage = function (event) {
      console.log('event received')
    }
  }, []);

但是window.onmessage永远不会触发或间歇性触发。

我通过将 window.onmessage 保持在 useEffect 之外进行检查,但它不起作用。

有人遇到过这个问题吗?需要帮助。

谢谢。

【问题讨论】:

  • 您好,您想尝试其他方式吗? (而不是向 iframe 发送消息)或者您必须使用发送消息?
  • 我必须与 iframe 通信。 postMessage 在父应用程序中实现,因此我必须添加 window.onmessage 或 window.addEventListner('message')。还有什么办法?
  • 在您的 react 源中的 componentDidMount() {window.parent.callMe = myFunc} 和您的父应用程序中只需调用 window.callMe(...your-parameters) 如果您对更多感兴趣,我可以给你看完整的示例代码
  • 谢谢,我的父母是用角写的。 iframe 应用程序正在做出反应。如果可能,请分享示例。

标签: reactjs iframe


【解决方案1】:

这是简单的代码,iframe 中的内容和父应用中的内容并不重要, 我们只需要在像window这样的全局变量上共享一个函数

在你的父应用中调用:

window.callMe('Hello world');
or
window.callMe({status:true, message:'hello world'});

在您的 iframe 中(在您的示例中做出反应)只需在父窗口上定义 callMe

myFunc=(data)=>{
    console.log(data);
}
window.parent.callMe = myFunc;

示例代码:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const callIframeFunc = () => {
    window.callMe("Hello");
  };
  return (
    <div className="App">
      <h1>React rel with iframe Demo</h1>
      <iframe
        id="unqiframe"
        title="a"
        srcDoc="<div><script>function myFunc(data){document.getElementsByClassName('testp')[0].innerHTML = 'received data : '+data} window.parent.callMe = myFunc;</script><p class='testp'>No data</p></div>"
        allow="autoplay"
      ></iframe>
      <div>
        <button onClick={callIframeFunc}>Call iFrame Func</button>
      </div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

DEMO

【讨论】:

  • 谢谢,但我收到 Property 'callMe' does not exist on type 'Window & typeof globalThis' 错误消息。
  • 你能分享我你的代码吗?你在哪里定义 callMe ?
  • 我认为您正在使用 TypeScript,如果为真,请尝试定义如下:stackoverflow.com/questions/12709074/… 或此:stackoverflow.com/questions/56457935/…
  • 嗨 Babak,感谢您的帮助。我正在尝试其他一些解决方案,在调试时我发现 postMessage 在 window.onmessage 之前运行,这就是事件没有收到的原因。
猜你喜欢
  • 2018-02-03
  • 2019-01-29
  • 1970-01-01
  • 2022-01-06
  • 2021-02-02
  • 2018-08-31
  • 2017-10-25
  • 2019-02-26
  • 1970-01-01
相关资源
最近更新 更多