html5 Postmessage解决跨域问题

 

在 Cross-document messaging 中使用 postMessage 和 onmessage

为了实现不同域之间的通信,需要在操作系统的 hosts 文件添加两个域名,进行模拟。

清单 3. hosts 文件中添加两个不同的域名
 127.0.0.1 	 parent.com 
 127.0.0.1 	 child.com

在父网页中通过 iframe 嵌入子页面,并在 JavaScript 代码中调用 postMessage 方法发送数据到子窗口。

清单 4. 父页面中嵌入子页面,调用 postMessage 方法发送数据
 <html> 
 <head> 
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
 <title>Test Cross-domain communication using HTML5</title> 
 <script type="text/JavaScript"> 
	 function sendIt(){ 
		 // 通过 postMessage 向子窗口发送数据
		 
	 } 
 </script> 
 </head> 
 <body> 
	 <!-- 通过 iframe 嵌入子页面 --> 
	 <iframe src="http://child.com:8080/TestHTML5/other-domain.html" 
				 id="otherPage"></iframe> 
	 <br/><br/> 
	 <input type="text" id="message"><input type="button" 
			 value="Send to child.com" onclick="sendIt()" /> 
 </body> 
 </html>

在子窗口中监听 onmessage 事件,并用 JavaScript 实现显示父窗口发送过来的数据。

清单 5. 子窗口中监听 onmessage 事件,显示父窗口发送来的数据
 <html> 
 <head> 
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
 <title>Web page from child.com</title> 
 <script type="text/JavaScript"> 
	 //event 参数中有 data 属性,就是父窗口发送过来的数据
	 window.addEventListener("message", function( event ) { 
		 // 把父窗口发送过来的数据显示在子窗口中
	   document.getElementById("content").innerHTML+=event.data+"<br/>"; 
	 }, false ); 

 </script> 
 </head> 
 <body> 
	 Web page from http://child.com:8080 
	 <div id="content"></div> 
 </body> 
 </html>

上班后,试试可行否。

你可能感兴趣的:(html5 Postmessage解决跨域问题)