• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

武飞扬头像
zx&it
帮助1

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

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

event 的属性有:

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

使用的场景:

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

  1.  
     
  2.  
    // localhost:9999/index页面
  3.  
    // 接收消息
  4.  
    window.addEventListener('message', (e) => {
  5.  
         console.log(e.data)
  6.  
    })
  7.  
    // 发送消息
  8.  
    const targetWindow = window.open('http://localhost:8888/user');
  9.  
    setTimeout(()=>{
  10.  
         targetWindow.postMessage('来自9999的消息', 'http://localhost:8888')
  11.  
    }, 3000)
  12.  
    /**
  13.  
     
  1.  
    // localhost:8888/user页面
  2.  
    window.addEventListener('message', (e) => {
  3.  
         console.log(e.data)
  4.  
         if (event.origin !== "http://localhost:9999"
  5.  
         return;
  6.  
         e.source.postMessage('来自8888的消息', e.origin)
  7.  
    })

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

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

  1.  
    <iframe id="iframe" src="./demoIframe"></iframe>
  2.  
     
  3.  
    <script>
  4.  
    var iframe = document.getElementById('iframe');
  5.  
    iframe.onload = function() {
  6.  
       // 向domain2发送跨域数据
  7.  
       iframe.contentWindow.postMessage('来自index.html的消息', 'index.html');
  8.  
    };
  9.  
    // 接受demoIframe返回数据
  10.  
    window.addEventListener('message',(e) => {
  11.  
        console.log(e.data);
  12.  
    }, false);
  13.  
    </script>

在iframe的demoIframe.html页面中:

  1.  
    <script>
  2.  
    // 接收index.html的数据
  3.  
    window.addEventListener('message',(e) => {
  4.  
        console.log(e.data);
  5.  
     
  6.  
        if(e.origin !== 'index.html')
  7.  
        return;
  8.  
        // 发送消息给index.html
  9.  
        window.parent.postMessage('来自demoIframe.html的消息', e.origin);
  10.  
    }, false);
  11.  
    </script>

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbeaib
系列文章
更多 icon
同类精品
更多 icon
继续加载