window.postMessage实现跨域通信

来源:互联网 发布:高校一卡通网络 编辑:程序博客网 时间:2024/06/05 02:31

# window.postMessage概述

1.html5最常用的API之一,实现两个不同域窗口对象之间的数据通信。

2.在发送数据窗口执行:otherWindow.postMessage(msg,origin)

  • otherWindow:表示接受数据的窗口的window对象,包括iframe的contentWindwohe和通过window.open打开的新窗口。
  • msg表示要发送的数据,包扩字符串和对象(ie9以下不支持,可以利用字符串和json互换)
  • origin表示接收的域名。
3.在接受的窗口监听window的message事件,回掉函数参数接受一个事件对象event,包括的属性有:
  • data:接受的数据
  • origin:发送端的域
  • source:发送端的DOMWindow对象
# 利用window.postMessage在框架之间发送数据
1.在父框架页面index.html发送obj对象给远程服务器的wozien.com/test/b.html,该页面是通过iframe加载的,如下
<!DOCTYPE html><html><head><title>window.postMessage</title></head><body><iframe id="proxy" src="http://wozien.com/test/b.html" onload = "postMsg()" style="display: none" ></iframe><script type="text/javascript">var obj = {msg: 'this is come from client message!'}function postMsg (){var iframe = document.getElementById('proxy');var win = iframe.contentWindow;win.postMessage(obj,'http://wozien.com');}</script></body></html>
2.在远程页面b.html中监听message事件,先通过origin属性判断下数据来源的域是否可信任,加强安全措施。具体代码如下:
<!DOCTYPE html><html><head><title></title><script type="text/javascript">window.onmessage = function(e){if(e.origin !== 'http://localhost') return;console.log(e.origin+' '+e.data.msg);}</script></head><body><p>this is my server</p></body></html>
3.在控制输出结果:

另外还可以在打开的新窗口中相互通信,具体查看相关链接演示。



0 0