iframe嵌入父页面,postMessage跨域传递消息

作者:@ywjbalabala
本文为作者原创,转载请注明出处:https://www.cnblogs.com/ywjbalabala/p/17273017.html


前言

掘金文章
使用window.postMessage可以帮助我们进行安全的跨源通信。
基本原理是通过postMessage来发送跨文档信息,使用message来进行监听,当收到跨文档信息后,会触发message事件

postMessage语法 > argetWindow.postMessage(message, targetOrigin, [transfer]);

targetWindow:

目标窗口的引用,比如执行window.open返回的窗口对象、打开当前窗口的引用window.opener、iframe的contentWindow属性,或者是命名过或数值索引的window.frames

message:

发送给目标window的数据

targetOrigin:

指定接收消息事件的窗口,其值可以是一个URI或者字符串""(表示无限制)
如果你明确的知道消息应该发送到哪个窗口,那么请始终提供一个有确切值的targetOrigin,而不是
。不提供确切的目标将导致数据泄露到任何对数据感兴趣的恶意站点。

transfer: 可选(本文对该项不做解释)

是一串和message 同时传递的 Transferable 对象. 这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权。

在Iframe里的使用

父传子

// A.html (父)
<iframe src="http://127.0.0.1:5501/B.html" frameborder="1" id="Bframe"></iframe>
const msg = {
name: "A"
}
window.onload = () => {
// 自动调用必须放在onload中,通过事件调用则不用
// let frame = document.querySelector("#Bframe").contentWindow //用锚点获取iframe
let frame = window.frames[0]
frame.postMessage(msg, "http://127.0.0.1:5501")
}
// B.html
window.addEventListener("message", (e) => {
console.log(e.data)
console.log(e.origin)
console.log(e.source)
})

子传父

// A.html (父)
<iframe src="http://127.0.0.1:5501/B.html" frameborder="1" id="Bframe"></iframe>
window.addEventListener("message", (e) => {
console.log(e.data)
console.log(e.origin)
console.log(e.source)
})
// B.html
const msg = {
name: "B"
}
window.top.postMessage(msg, "http://127.0.0.1:5500")

图片

父页面


iframe页面

posted @   lalibaba  阅读(431)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示