html5 JS跨域通信

主頁面:http://ext.js.com

跨域:http://hb.test.com

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>跨域通信示例</title>
<script type="text/javascript">
	window.addEventListener("message",function(ev){
	
		if(ev.origin != "http://hb.test.com"){
			return;
		}
		
		document.getElementById("h").innerHTML = "從"+ev.origin + "那裏傳過來的消息:\n" + ev.data ;
		},false);

		function hello(){
			var iframe= window.frames[0];
			iframe.postMessage("你好","http://hb.test.com");
		}

</script>
</head>
<body>
	<h1>跨域通信</h1>
	<iframe width="400" src="http://hb.test.com/a1.html" onload="hello()"></iframe>
	<div id="h">

	</div>
</body>
</html>









iframe頁面

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>跨域通信示例</title>
<script type="text/javascript">
	window.addEventListener("message",function(ev){
		
		if(ev.origin != "http://ext.js.com"){
			return;
		}
		document.body.innerHTML="從"+ev.origin + "那裏傳來的消息。<br />" + ev.data ;
		ev.source.postMessage("您好,這裏是"+this.location, ev.origin);
	},false);
</script>
</head>
<body>

	
</body>
</html>





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章