美文网首页
html5的postMessage简易通俗使用说明

html5的postMessage简易通俗使用说明

作者: 果好鲜 | 来源:发表于2019-05-25 11:44 被阅读0次

    其中的三种场景

    1. 可以实现页面和里面iframe页面之间的通讯
    背景:页面A中通过iframe嵌入B页面
    • A页面要提交消息给B页面
    iframeEle.contentWindow.postMessage() 
    
    • B页面要提交消息给A页面
    window.parent.postMessage()
    
    1. 可以实现窗口和通过window.open的窗口间的通讯
    背景:页面A通过调用window.open()打开B页面
    • A页面向B页面发送消息
    // 
    var openWindow = window.open()
    // 如果直接openWindow.postMessage()是不行的,要异步才可以的
    setTimeout(function(){
      openWindow.postMessage()
    })
    
    • B页面向A页面发送消息
    window.opener.postMessage()
    
    1. 可以实现窗口和通过a标签新打开的窗口间的通讯
    背景:A页面里面有一个例如:<a href="B页面" target="_blank">新打开B页面</a>这样的一个a标签,能够新窗口中打开一个B页面
    • B页面向A页面发送消息
    window.opener.postMessage()
    
    • 如果A页面想要给B页面也返回消息的话,可以利用message响应事件中的source属性来实现
    window.addEventListener('message', function(event){
      event.source.postMessage()
    })
    

    对于上面这三种使用,对应接受消息的页面,也应该有window.addEventListener('message', function(){})的,这里就省略了,请知道!

    然后window.addEventListener("message", receiveMessage, false);中,对于receiveMessage函数中,有event对象,其中包括data,origin,source这几个属性。

    • data 接收到的消息
    • origin 调用 postMessage 时消息发送方窗口的origin
    • source 对发送消息的窗口对象的引用; 所以可以使用此来在具有不同origin的两个窗口之间建立双向通信。

    相关文章

      网友评论

          本文标题:html5的postMessage简易通俗使用说明

          本文链接:https://www.haomeiwen.com/subject/ikeazqtx.html