iframe父子窗口通信
在业务开发中,经常有需要某个页面嵌入iframe,同时还需要与iframe进行通信。
1. 子窗口对父窗口发出消息
window.parent.postMessage(参数1为发送的消息数据,参数2为可以接受到消息的源)
window.parent.postMessage({ 'type': '自定义事件名', // 自定义事件名 'value':JSON.stringify(ObjData) // 数据,只能是字符串 }, '*');
2. 父窗口接受消息
window.addEventListener('message', 事件名, false);
mounted() { window.addEventListener('message', this.receiveMsg, false); },
beforeUnmount() { window.removeEventListener('message', this.receiveMsg, false); },
methods:{
receiveMsg(e){
// e.data = 子窗口发送消息传来的数据,上面示例这里就会接受到 {type:"事件名",value:"字符串数据"} } }
3. 父窗口向子窗口发送消息
Iframe.contentWindow.postMessage(消息,源)
注意:只有当iframe加载完毕,即onLoad完成后,才能接收到消息,所以当load完毕后父窗口再去发送消息,不然发了也白发。
<template> <iframe class="map" src="xxxx" @load="iframeLoad"/> </template> <script> export default {
data(){
return {
loadFinish:false
}
}, methods:{ postMessage() {
if(!this.loadFinish)return this.$el.querySelector('.map').contentWindow.postMessage('主页面消息', '*'); },
iframeLoad(){
this.loadFinish = true
}
}
} </script>
4. 子窗口接收消息
子窗口接收消息和父窗口接收消息一样的。window.addEventListener('message', 事件名, false);
mounted() { window.addEventListener('message', this.receiveMsg, false); }, beforeUnmount() { window.removeEventListener('message', this.receiveMsg, false); }, methods: { receiveMsg(e) { console.log(e) // e.data 就是发送过来的消息 上面的示例,那 e.data = "主页面消息" } }
标签:
iframe
, iframe父子窗口通信
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库