使用postMessage实现iframe和父页面通信

语法

语法
otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow 其他窗口的一个引用,例如向子窗口发送 则otherWindow 是子窗口的window对象

父页面向子页面Iframe通信

// 父页面
     //获取iframe元素
    const iFrame:SafeAny = document.getElementById('myFrame')

    //iframe加载完毕后再发送消息,否则子页面接收不到message
    iFrame.onload = function(){

     //iframe加载完立即发送一条消息 iframe.contentWindow返回的是iframe的window对象 
     iFrame.contentWindow.postMessage('message1','*');
    }
// 子页面
    window.addEventListener('message', function (e) {
			try {
				console.log(e.data) // message1  
			} catch (error) {
				console.log(error)
			}
		},false)

子页面Iframe向父页面通信

// 子页面
// 注意要使用父页面的window window.parent
    window.parent.postMessage(JSON.stringify('message2','*');
// 父页面
     window.addEventListener('message', function (e) {
      try {
        console.log(e.data) // message2  
      } catch (error) {
        console.log(error)
      }
    },false)
posted @   DurianTRY  阅读(404)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示