React使用iframe父传子

window.postMessage

window.postMessage() 方法可以安全地实现跨源通信。通常,对于两个不同页面的脚本,只有当执行它们的页面位于具有相同的协议(通常为 https),端口号(443 为 https 的默认值),以及主机 (两个页面的模数 Document.domain设置为相同的值) 时,这两个脚本才能相互通信。window.postMessage() 方法提供了一种受控机制来规避此限制,只要正确的使用,这种方法就很安全。

子传父

import React, { useEffect } from 'react';

  const Index = () => {

    useEffect(() => {

      window.addEventListener('message', function (event) {

        if (event.data == 'close') {

          console.log('获取到子应用传递过来的值');

          console.log(event);

        }

      });

    }, []);

    return (

     

       

     

    );

  };

  export default Index;

/

父传子

```import React, { useEffect, useRef } from 'react';

import styles from './index.less';

import request from '@/utils/request';

const index: React.FC = () => {

  const createIframe = (src: string, element: string, v: object) => {

    const token = window.localStorage.getItem('currentAccess');

    const params = { Authorization: `Bearer ${token}`, level: v.level };

    // 在此元素上添加iframe

    const childFrameObj: any = document.getElementById(element);

    const iframe: any = document.createElement('iframe');

    iframe.src = src;

    childFrameObj.appendChild(iframe);

    // 判断iframe是否加载完成

    if (iframe.attachEvent) {

      iframe.attachEvent('onload', () => {

        iframe.contentWindow.postMessage(params, '*');

      });

    } else {

      iframe.onload = () => {

        iframe.contentWindow.postMessage(params, '*');

      };

    }

  };

  const CRFGetRequest = () => {

    request.get('/*/crf/user/get_userInfo').then((res) => {

      createIframe(

        '传入的URL',

        'calculation',

        需要传入的参数,

      );

    });

  };

  useEffect(() => {

    CRFGetRequest();

  }, []);

  return (

   

     

   

  );

};

export default index;```

你可能感兴趣的:(React使用iframe父传子)