本文主要是介绍iframe 子父页面互相通信,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
知识点
1、父页面向子页面发送消息const idIframe = document.getElementById("idIframe").contentWindowconst 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").contentWindowconst data = {data: 10000}idIframe.postMessage(data, '*');}render() {const { loading } = this.statereturn(<><Spin spinning={loading}><Button onClick={this.sendMessage}>向iframe传值的方法</Button><iframeid={"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></>);}
}
这篇关于iframe 子父页面互相通信的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!