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