通过postMessage在iframe和父窗口之间通信

postMessage是HTML5引入的一种用于跨文档通信的方法,允许不同源的页面进行安全的数据交换。数据可以是任意类型,而origin参数用于指定接收消息的窗口源。在父子窗口之间,可以通过监听message事件来接收和发送消息。例如,子窗口可以通过parent.postMessage向父窗口发送数据,而父窗口则可以通过window.frames[0].postMessage向iframe发送数据,并通过message事件的回调处理接收到的数据,回调中包含data、origin和source等关键信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

window.postMessage

在 HTML5 中新增了 postMessage 方法,postMessage 可以实现跨文档消息传输(Cross Document Messaging)

postMessage(data,origin)

  • data:要传的数据
  • origin: 字符串参数,指明目标窗口的源,协议+主机+端口号。如果为*则是所有的窗口,如果要指定和当前窗口同源的话设置为"/"。

iframe 向 父窗口通信:

子窗口向父窗口发送消息,其实是在子窗口里拿到父窗口的句柄,然后用父窗口的postMessage去发送内容。

//iframe
const parent = window.parent;
parent.postMessage(data, '*')

//父页面
window.addEventListener(
  'message',
  function(e) {
  	console.log(e);
    console.log(e.data);
  },
  false
)

父窗口 向 iframe 通信

//父页面
window.frames[0].postMessage(data, 'http://test.com:port') //第二个参数为子页面地址

//iframe
window.addEventListener(
  'message',
  function(e) {
    if (e.source != window.parent) return
    console.log(e.data)
    // message的回调里有三个非常重要的属性:data、origin、source
    // e.data:从其他窗口带过来的数据
    // e.origin:调用 postMessage 时消息发送方窗口的 origin . 这个字符串由 协议、“://“、域名、“ : 端口号”拼接而成。
    // e.source:对发送消息的窗口对象的引用; 您可以使用此来在具有不同 origin 的两个窗口之间建立双向通信。
   // 例如:event.source.postMessage("hi there yourself!  the secret response " + "is: rheeeeet!", event.origin);
  },
  false
)

1、contentWindow
document.getElementById(“myiframe”).contentWindow,
得到iframe对象后,就可以通过contentWindow得到iframe包含页面的window对象了

在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

. . . . .

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值