postMessage消息传递——window.addEventListener的运用。实现不同框架之间混用时(iframe),页面或组件之间相互传值。

window.postMessage() 方法允许来自一个文档的脚本可以传递文本消息到另一个文档里的脚本,不用管是否跨域。一个文档里的脚本还是不能调用在其他文档里方法和读取属性,但他们可以用window.postMessage结合window.addEventListene这种消息传递技术来实现安全的通信。

window.addEveantListener('message',(event)=>{}) 

event 的属性有:

  • data: 从其他 window 传递过来的数据副本。 
  • origin: 调用 postMessage 时,消息发送窗口的 origin。例如:“http://www.localhost:8080”。
  • source: 对发送消息的窗口对象的引用。可以使用此来在具有不同 origin 的两个窗口之间建立双向数据通信。

使用的场景:

1. 不同 origin 的两个窗口之间建立双向数据通信(不同端口下的窗口,不能网站地址)


// localhost:9999/index页面
// 接收消息
window.addEventListener('message', (e) => {
     console.log(e.data)
})
// 发送消息
const targetWindow = window.open('http://localhost:8888/user');
setTimeout(()=>{
     targetWindow.postMessage('来自9999的消息', 'http://localhost:8888')
}, 3000)
/**
// localhost:8888/user页面
window.addEventListener('message', (e) => {
     console.log(e.data)
     if (event.origin !== "http://localhost:9999") 
     return;
     e.source.postMessage('来自8888的消息', e.origin)
})

2. 页面与嵌套的 iframe 消息传递

在引用iframe的index.html页面中:

<iframe id="iframe" src="./demoIframe"></iframe>

<script>
var iframe = document.getElementById('iframe');
iframe.onload = function() {
   // 向domain2发送跨域数据
   iframe.contentWindow.postMessage('来自index.html的消息', 'index.html');
};
// 接受demoIframe返回数据
window.addEventListener('message',(e) => {
    console.log(e.data);
}, false);
</script>

在iframe的demoIframe.html页面中:

<script>
// 接收index.html的数据
window.addEventListener('message',(e) => {
    console.log(e.data);
 
    if(e.origin !== 'index.html')
    return;
    // 发送消息给index.html
    window.parent.postMessage('来自demoIframe.html的消息', e.origin);
}, false);
</script>
  • 10
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值