知识点
1、父页面向子页面发送消息
const idIframe = document.getElementById("idIframe").contentWindow
const data = {data: 10000}
idIframe.postMessage(data, '*');
2、子页面向父页面发送消息
const data = {data: 10000}
window.parent.postMessage(data , "*");
3、接收消息方法
window.addEventListener('message', function (e) {
// do something
})
父页面
import React, { useState } from 'react';
import {Spin, Button} from 'antd'
export default class IframeIndex extends React.Component {
refIframe = React.createRef()
constructor() {
super()
this.state ={
loading: true
}
}
componentDidMount(){
const idIframe = document.getElementById("idIframe")
idIframe.onload = () => {
this.setState({
loading: false
})
}
window.addEventListener("message", this.handleMessage)
}
/**
* 监听子页面传过来的值的方法
* @param {Object} event
*/
handleMessage(event) {
console.log(event, '监听子页面传过来的值的方法');
// do something
}
/**
* 向iframe传值的方法
* @param {Object} data
*/
sendMessage = () => {
const idIframe = document.getElementById("idIframe").contentWindow
const data = {data: 10000}
idIframe.postMessage(data, '*');
}
render() {
const { loading } = this.state
return(
<>
<Spin spinning={loading}>
<Button onClick={this.sendMessage}>向iframe传值的方法</Button>
<iframe
id={"idIframe"}
ref={this.refIframe}
frameBorder="0"
src={'http://localhost:8000/iframe/child'}
width={"100%"}
height={"400px"}
></iframe>
</Spin>
</>
)
}
}
子页面
import React, { useState } from 'react';
import { Button } from 'antd';
export default class IframeIndex extends React.Component {
constructor() {
super();
this.state = {};
}
componentDidMount() {
// 监听postMessage 数据
window.addEventListener('message', (e) => {
console.log(e);
});
}
/**
* 向iframe传值的方法
* @param {Object} data
*/
sendMessage = () => {
const idIframe = document.getElementById('idIframe').contentWindow;
const data = { data: 10000 };
idIframe.postMessage(data, '*');
};
render() {
return (
<>
<div style={{ padding: '10px' }}>
<Button size='small' onClick={() => this.postMessage()}>向父页面传值</Button>
</div>
</>
);
}
}