繁体   English   中英

当 html 页面已经通过 Reactjs 中的 Iframe 打开时,如何检测 addEventlistener

[英]How to detect addEventlistener when html page is already opened via Iframe in Reactjs

我想检测我在 ReactApp 中的更改,并希望在通过 Iframe 打开的 Html 页面中应用这些更改。

场景:我想使用 PostMessage 处理程序将我选择/更改的数据更新到我已经打开的 html 页面中。

我用“window.postMessage”和“window.AddEventlistener”试过这个,但我的改变没有在这里反映出来。 我需要改变什么才能完成这项工作。 有什么建议吗?

//test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
    <script>
      window.addEventListener("message", receiveMessage, false);

      function receiveMessage(event)
      
      {
        if(event) {
          
          console.log(event.target.value, "hello"); // The idea is too receive the device selected 
        }
        
      }
    </script>
    
</head>
<div>
  <tr>
    Hii
  </tr>
</div>
</body>
</html>

//ReactApp 页面

  handleSelectDevice(type, event) {

    window.postMessage(JSON.stringify({'data': event.target.value}), "*");

  }

//IframeReactjs 页面

class Test extends React.Component {

  render() {
    const testUrl = process.env.PUBLIC_URL+"/test.html";
    return (
      <Iframe id="testid" src={testUrl} width="100%" height={240} />
    );
  }
}

export default Test;

使用useRef挂钩获取 iframe 引用,然后使用HTMLIFrameElement.contentWindow调用postMessage function

class Test extends React.Component {
  render() {
    const testUrl = process.env.PUBLIC_URL + "/test.html";
    return (
      <Iframe
        ref={this.props.innerRef} //--> pass reference as property
        id="testid"
        src={testUrl}
        width="100%"
        height={240}
      />
    );
  }
}

然后在 app.js

 const ref = useRef(null); // reference to iframe

 handleSelectDevice(type, event) {
     // --> postMessage to the iframe
     ref.current.contentWindow.postMessage(JSON.stringify({'data': event.target.value}), "*");
 }

<Test innerRef={ref}/>

测试.html

window.addEventListener("message", (event) => {
  console.log(event); // --> listen for messages
});

您可以使用event.data获取消息数据,更多详细信息请点击此处

调用postMessage()时,您需要使用 iframe 的“窗口”,而不是主window object。

考虑到ifr是一个引用 (HTMLIFrameElement) 中的 iframe 元素的变量,它的 window 是在ifr.contentWindow中定义的,所以调用类似于

ifr.contentWindow.postMessage(...);

更多细节在这里: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

更新:
此处的虚拟工作示例: https://codesandbox.io/s/react-example-createref-postmessage-nh881?file=/src/App.js

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM