window.postMessage实现跨域通信

# 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.在控制输出结果:

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值