天天看点

HTML5 postMessage解决跨域|跨窗口通信

知识拓展

postMessage()

方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递。

语法

postMessage(data,origin)

方法接受两个参数

  • data

    :要传递的数据

    html5

    规范中提到该参数可以是

    JavaScript

    的任意基本类型或可复制的对象,然而并不是所有浏览器都做到了这点儿,部分浏览器只能处理字符串参数,所以我们在传递参数的时候需要使用

    JSON.stringify()

    方法对对象参数序列化,在低版本IE中引用

    json2.js

    可以实现类似效果。
  • origin

    :字符串参数

    -指明目标窗口的源,

    协议+主机+端口号[+URL]

    ,URL会被忽略,所以可以不写,这个参数是为了安全考虑,postMessage()方法只会将message传递给指定窗口,当然如果愿意也可以建参数设置为"

    *

    ",这样可以传递给任意窗口,如果要指定和当前窗口同源的话设置为"

    /

    "。

实现方法

发送消息

http://a.com/index.html

<div style="width:200px; margin-right:200px; border:solid 1px #333;">
        <div id="color">Frame Color</div>
    </div>
    <div>
    <iframe id="child" src="http://b.com/lsLib.html"></iframe>
</div>
           

http://a.com/index.html

通过

postMessage()

方法向跨域的

iframe

页面http://b.com/lsLib.html传递消息

window.onload=function(){
 var iframe = document.getElementById('child').contentWindow;
 iframe.postMessage('getcolor','http://b.com');
}
           

接收消息

a.com 上面的页面向 b.com 发送了消息,通过监听

window

message

事件就可以获取到洗洗

http://b.com/lslib.html

window.addEventListener('message',function(e){
 if(e.source != window.parent) return;
    var color=container.style.backgroundColor;
    window.parent.postMessage(color,'*');
},false);
           

为了安全起见,我们利用这时候的

MessageEvent

对象判断了一下消息源,

MessageEvent

体如下图:

HTML5 postMessage解决跨域|跨窗口通信

解析:

data

:顾名思义,是传递来的message

source

:发送消息的窗口对象

origin

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

方向传递消息

iframe

接收消息,并把当前颜色发送给主页

window.addEventListener('message',function(e){
  if(e.source!=window.parent) return;
    var color=container.style.backgroundColor;
    
    window.parent.postMessage(color,'*');
},false);
           

主页面接收消息,更改自己div颜色

window.addEventListener('message',function(e){
 var color=e.data;
    document.getElementById('color').style.backgroundColor=color;
},false);
           

当点击iframe事触发其变色方法,把最新颜色发送给主页面

function changeColor () {            
   var color=container.style.backgroundColor;
    if(color=='rgb(204, 102, 0)'){
        color='rgb(204, 204, 0)';
    }else{
        color='rgb(204,102,0)';
    }
    container.style.backgroundColor=color;
    window.parent.postMessage(color,'*');
}
           

主页面还是利用刚才监听message事件的程序处理自身变色

window.addEventListener('message',function(e){
   var color=e.data;
    document.getElementById('color').style.backgroundColor=color;
},false);
           

参考资料:

https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage

继续阅读