iframe——父子域通信

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_37246828/article/details/102716739

场景描述:前端常用iframe来嵌入其他域名页面,通常只是静态展示;如果是自己系统群的两个站点嵌套,则可以通过代码配合实现互相通信,实现父子域相互操作。前提是父子域名相同,否则浏览器出于安全协议会阻止跨域操作。

我的需求:
https://mh.cmft.com站点需要嵌入https://fhdmp.cmft.com站点的页面,且通过操作https://mh.cmft.com可以触发https://fhdmp.cmft.com页面的事件。
以下https://mh.cmft.com称A,https://fhdmp.cmft.com称B

A的配置:

// A嵌入B
<iframe id="iframeId" src="https://fhdmp.cmft.com/dataEntry/baseData/dataImport/index"></iframe>
// 向B发送数据
document.getElementById('iframeId').contentWindow.postMessage(postData, 'https://fhdmp.cmft.com')

// 绑定message事件和用于B来触发的函数receiveMsg
window.addEventListener('message', this.receiveMsg, false)
// receiveMsg接收B的触发,e为事件对象
receiveMsg (e) {
  console.log(e.data) // B发送的数据
},

B的配置:

// 绑定message事件和用于A来触发的函数receiveMsg
window.addEventListener('message', this.receiveMsg, false)
// receiveMsg接收A的触发,e为事件对象
receiveMsg (e) {
  console.log(e.data) // A发送的数据
},
// B像A发送数据
postDataToPrent (val) {
  window.top.postMessage(val, 'https://mh.cmft.com')
}

猜你喜欢

转载自blog.csdn.net/qq_37246828/article/details/102716739