实现两个窗口通讯方法-postMessage

postMessage

  1. otherWindow:其余窗口的一个引用,好比iframe的contentWindow属性、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames。javascript

  2. message:将要发送到其余 window 的数据。它将会被结构化克隆算法序列化。这意味着你能够不受什么限制的将数据对象安全的传送给目标窗口而无需本身序列化。html

  3. targetOrigin:经过窗口的origin属性来指定哪些窗口能接收到消息事件,其值能够是字符串”“(表示无限制)或者一个URI。在发送消息的时候,若是目标窗口的协议、主机地址或端口这三者的任意一项不匹配targetOrigin提供的值,那么消息就不会被发送;只有三者彻底匹配,消息才会被发送。这个机制用来控制消息能够发送到哪些窗口;例如,当用postMessage传送密码时,这个参数就显得尤其重要,必须保证它的值与这条包含密码的信息的预期接受者的orign属性彻底一致,来防止密码被恶意的第三方截获。若是你明确的知道消息应该发送到哪一个窗口,那么请始终提供一个有确切值的targetOrigin,而不是。不提供确切的目标将致使数据泄露到任何对数据感兴趣的恶意站点。java

  4. transfer:是一串和message 同时传递的 Transferable 对象. 这些对象的全部权将被转移给消息的接收方,而发送一方将再也不保有全部权。

message 的一些属性

  1. data:从其余 window 中传递过来的对象。
  2. origin:调用 postMessage 时消息发送方窗口的 origin . 这个字符串由 协议、“://“、域名、“ : 端口号”拼接而成。例如 “https://example.org (implying port 443)”、“http://example.net (implying port 80)”、“http://example.com:8080”。请注意,这个origin不能保证是该窗口的当前或将来origin,由于postMessage被调用后可能被导航到不一样的位置。
  3. source:对发送消息的窗口对象的引用; 您可使用此来在具备不一样origin的两个窗口之间创建双向通讯。

实现通讯demo:

// a.com/index.html
<iframe src='b.com/index.html' id='iframe'></iframe>
<script>
    window.onload = function(){
        var iframe = document.getElementById('iframe');
        // 若写成'http://b.com/c/proxy.html'效果同样
        // 若写成'http://c.com'就不会执行postMessage了
        var targetOrigin = 'http://b.com';
        iframe.contentWindow.postMessage('data to send',targetOrigin);
    }
</script>
// b.com/index.html
<script type="text/javascript">
  window.addEventListener('message',function(event){
    // 经过origin属性判断消息来源地址
    if(event.origin == 'http://a.com'){
      console.log(event.data);
      console.log(event.source);
    }
  },false);
</script>
相关文章
相关标签/搜索