iframe 跨域通信,子页面向父页面发送消息,自动关闭父页面弹窗
前言
使用iframe跨域嵌套了一个子页面,子页面操作完成后,需要在父页面自动关闭子页面
实现思路
1、打开弹窗时,在window对象下,封装关闭弹窗的对象
export default {
methods: {
// 打开弹窗
open(){
...
// 在window对象下,封装关闭弹窗的对象
window.childrenDialog = {
dialogThis: this,
close: function(){
window.childrenDialog.dialogThis.close()
}
}
}
// 关闭弹窗
close(){
...
}
}
}
2、统一监听子页面消息,子页面发送关闭弹窗的消息时,关闭弹窗
window.addEventListener('message',function(e){
if(e.data === 'closeDialog'){// 关闭对话框
window.childrenDialog.close()
}
)
3、子页面向父页面发送消息,关闭弹窗
parent.postMessage('closeDialog','*')
正文到此结束