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

导读:本篇文章讲解 postMessage消息传递——window.addEventListener的运用。实现不同框架之间混用时(iframe),页面或组件之间相互传值。,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

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>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/66306.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!