Html5 postMessage实现跨域消息传递

2020-04-21 07:22:30易采站长站整理

XML/HTML Code复制内容到剪贴板

window.addEventListener(‘message’,function(e) {   
       
}  

    onmessage事件接受一个参数e,它是一个event对象。

    e的几个重要属性:

      1、data:postMessage传递过来的msg

      2、发送消息的窗口对象

      3、origin:发送消息窗口的源(协议+主机+端口号)

     来写一个简单的demo:

     http://source.com/source.html用来发送数据:

XML/HTML Code复制内容到剪贴板

<iframe id="iframe" src="http://target.com/target.html"></iframe>  
<input id="msg" type="text" placeholder="请输入要发送的消息">  
<button id="send">发送</button>  
  

JavaScript Code复制内容到剪贴板

window.onload =function() {   
    document.getElementById(‘send’).onclick = function() {   
    var msg = document.getElementById(‘msg’).value;   
    var iframeWindow = document.getElementById(‘iframe’).contentWindow;   
    iframeWindow.postMessage(msg,"http://target.com/target.html");   
    }   
}   

     http://target.com/target.html用来接收数据: 

XML/HTML Code复制内容到剪贴板

<div>  
   <h2>target.html,以下是接收到的消息:</h2>  
    <section id="msg">  
           
    </section>  
</div>  

JavaScript Code复制内容到剪贴板

window.onload = function() {   
  
    if(window.addEventListener){   
        window.addEventListener("message", handleMessage, false);   
    }   
    else{   
        window.attachEvent("onmessage", handleMessage);   
    }     
  
    function handleMessage(event) {   
        event = event || window.event;