Html5 跨域通信

H5 跨域通信:

在主页面中通过iframe嵌入外部页面,通过iframe的window对象postMessage方法向iframe页面传递消息。

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title>跨域通信示例</title>
 6         <script type="text/javascript">
 7             function hello(){
 8                 var iframe = document.getElementById("iframe").contentWindow;
 9                 iframe.postMessage("hello, 这是主页面传过来的数据", "http://localhost/html5/b.html");
10             }
11         </script>
12     </head>
13     <body>
14         <h1>跨域通信示例</h1>
15         <iframe width="400" src="http://localhost/html5/b.html" onload="hello()" id="iframe">
16         </iframe>
17     </body>
18 </html>

iframe页面中通过对窗口对象的message事件进行监听,以获取消息。

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <script type="text/javascript">
 6             window.addEventListener("message", getEvent, false);
 7             function getEvent(event){
 8                 alert("" + event.origin + "那里传递过来的信息是:\n" + event.data);
 9             }
10         </script>
11     </head>
12     <body>
13         iframe 页面
14     </body>
15 </html>

  

posted @ 2012-11-04 17:39  HappyCorn  阅读(2021)  评论(0编辑  收藏  举报