html5跨文档消息传输

1. 什么是跨域?

一句话:同一个IP、同一个网络协议、同一个端口,三者都满足就是同一个域。否则就会跨域访问。

2. html5如何实现跨文档消息传输?

首先,要是想接受从其他的窗口那里发送的消息,就必须对窗口对象的message事件进行监视。代码如下

window.addEventListener("message",function(){},false)

使用window对象的postMessage方法向其他窗口发送消息,其方法定义如下

otherWindow.postMessage(message,targetOrigin)

该方法第一个参数为所发送的消息文本

该方法第二个参数接收消息的URL地址


代码:

<html>
<head>
<meta charset="utf-8"/>
<title>跨域通信实例</title>
<script type="text/javascript">

window.addEventListener("message",function(ev){
	if(ev.origin !="http://localhost:8082"){
		return ;
		}
		alert("from "+ev.origin);
	
	},false);
	
function hello(){
	var iframe=window.frames[0];
	iframe.postMessage("你好!","http://localhost:8082");
	}
</script>
</head>
<h1>跨域通信实例</h1>
<iframe width="400" src="http://localhost:8082" onload="hello()"></iframe>
</html>

<html>
<head>
<meta charset="utf-8"/>
<title>跨域通信实例</title>
<script type="text/javascript">
window.addEventListener("message",function(ev){
	if(ev.origin !="http://localhost:8083"){
		return ;
		}
		document.body.innerHTML="from " +ev.origin+" data:"+ev.data;
		ev.source.postMessage("你好  这里是"+this.location,ev.origin);
	
	},false);
	

</script>
</head>
<body>aaaaaaaaaaaaaaaaa</body>
</html>



你可能感兴趣的:(html5跨文档消息传输)