iframe子页面与父页面通信方案,下面主要介绍父页面与子页面通信方案,根据自己需求做调整,通信方法都类似,以下是案例请参考
一:父页面(调用iframe的页面)父页面中引入iframe
第一步:页面中引入iframe
<iframe
id="PanIframe"
ref={iframeRef}
frameBorder={0}
width={960}
height={600}
marginHeight={0}
scrolling="no"
src={yunPanUrls}
></iframe>
第二步:父页面中监听iframe中发送过来的消息
window.addEventListener('message', receiveMessageIframePage, false);
第三步:监听到消息之后处理自身的业务逻辑或者与iframe页面通信都可以
getBoundFileKeys:是iframe页面内部暴露出来的方法,我们在父页面监听这个方法iframes.contentWindow.postMessage: 是发送给iframe的方法,方法名boundFileKeys
const receiveMessageIframePage = (event) => {
let iframes = document.getElementById('PanIframe'); // 获取iframe元素
// 如果监听到iframe暴露出一个type是getBoundFileKeys的消息,初始化给iframe发送一个boundFileKeys消息,做初始化的操作
if (event.data.type === 'getBoundFileKeys') {
iframes.contentWindow.postMessage({ type: 'boundFileKeys', data: "消息内容体" }, '*');
}
if (event.data.type === 'check') {
// 监听iframe暴露出来的check方法
}
}
二:子页面(iframe页面)
发送消息给父页面获取初始化信息数据或其他业务
window.parent.postMessage({
type: 'getBoundFileKeys'
}, '*');
监听父页面发送过来的消息
window.addEventListener('message', onMessage, false); // 接收接入方页面发送的消息
const onMessage = (e) => {
if (!e || !e.data) { return; }
switch (e.data.type) {
case 'boundFileKeys':
// TODO 处理自己的业务
break;
}
};
发送消息给接入方页面
isInIframe && window.parent.postMessage({
type: 'check', //自定义名称
data: ["自定义需要发送的数据"] // 处理数据
}, '*');
优化:判断是否处于iframe中
getIsInIframe() {
return window.self !== window.top;
}
总结:使用到的就是下面这几个方法
父页面监听iframe消息:
window.addEventListener('message', receiveMessageIframePage, false);
父页面发送给iframe页面的消息:
iframes.contentWindow.postMessage({ type: 'boundFileKeys', data: "消息内容体" }, '*');
iframe页面监听父页面发过来的消息:
window.addEventListener('message', onMessage, false);
iframe页面给父页面发送消息:
window.parent.postMessage({ type: 'check', data: ["自定义需要发送的数据"] }, '*');
交流
1、QQ群:可添加qq群共同进阶学习: 进军全栈工程师疑难解 群号: 856402057
2、公众号:公众号「进军全栈攻城狮」 ,对前端技术保持学习爱好者。我会经常分享自己所学所看的干货,在进阶的路上,共勉!