最新消息:

html5 postMessage解决跨域、跨窗口消息传递

工作 admin 2343浏览 0评论

一、页面向被嵌套的iframe发送消息:

<!DOCTYPE html>
<title>页面向被嵌套的iframe发送消息</title>
<script>

function sendStatus() {
    var statusText = document.getElementById("statusText").value;
    document.getElementById("widget").contentWindow.postMessage(statusText,'*');
}
</script>

传递信息:
<input type="text" id="statusText" value="Online">
<button id="sendButton" onclick=sendStatus()>确定</button>
<iframe id="widget" src="5.html"></iframe>

iframe页面:

<!DOCTYPE html>
<title>iframe</title>
<script>

function messageHandler(e) {
    document.getElementById("status").textContent = e.data;
}
window.addEventListener("message", messageHandler, true);

</script>
<p>显示接收信息: <strong id="status"></strong><p>

 

20140807151851

上面的例子是向子页面发送消息,如果子页面想向父页面发送消息,则使用window.parent.postMessage()即可。

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

postMessage(data,origin)方法接受两个参数
 1.data:要传递的数据,html5规范中提到该参数可以是JavaScript的任意基本类型或可复制的对象,然而并不是所有浏览器都做到了这点儿,部分浏览器只能处理字符串参数,所以我们在传递参数的时候需要使用JSON.stringify()方法对对象参数序列化,在低版本IE中引用json2.js可以实现类似效果。
2.origin:字符串参数,指明目标窗口的源,协议+主机+端口号[+URL],URL会被忽略,所以可以不写,这个参数是为了安全考 虑,postMessage()方法只会将message传递给指定窗口,当然如果愿意也可以建参数设置为”*”,这样可以传递给任意窗口,如果要指定和 当前窗口同源的话设置为”/”。
发送消息时调用otherWindow.postMessage(message, targetOrigin); 其中otherWindow: 指目标窗口,是 window.frames 属性的成员或者由 window.open 方法创建的窗口。
页面要想接收postMessage发送的消息,需要使用
window.addEventListener("message", function( event ) { 	   document.getElementById("content").innerHTML+=event.data+"<br/>";

或onmessage()来绑定消息事件。

回调函数第一个参数接收 Event 对象,有三个常用属性:

data: 消息
origin: 消息来源地址
source: 源 DOMWindow 对象
message 事件在低版本浏览器下模拟实现

参考资料:
1、http://www.2cto.com/kf/201312/263245.html
2、http://www.php100.com/html/program/html5/2013/0905/5442.html
3、http://www.cnblogs.com/wshiqtb/p/3171199.html
4、http://www.36ria.com/3890
5、http://www.ibm.com/developerworks/cn/web/1301_jiangjj_html5message/

转载请注明:jinglingshu的博客 » html5 postMessage解决跨域、跨窗口消息传递

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址