html5 跨文档消息传输示例

主页面:

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="gbk">
 5         <title>跨域通信实例</title>
 6     </head>
 7     <body>
 8         <h1>跨域通信实例</h1>
 9         <iframe width="400" src="http://b/test_html.htm" onload="hello()"></iframe>
10         
11         <script>
12             //监听message事件
13             window.addEventListener("message", function(e){
14                 //忽略指定url之外的页面传过来的消息
15                 if(e.origin != "http://b.com"){
16                     return;
17                 }
18                 //显示消息
19                 alert("" + e.origin + "那里传过来的消息:\n\"" + e.data + "\"");
20             },false);
21             function hello(){
22                 var iframe = window.frames[0];
23                 //传递消息
24                 iframe.postMessage("你好", "http://b/test_html.htm");
25             };
26         </script>
27     </body>
28 </html>

iframe页面:

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="gbk">        
 5     </head>
 6     <body>            
 7         <script type="text/javascript">
 8             alert("ok");
 9             window.addEventListener("message", function(e){
10                 if(e.origin != "http://a.com"){
11                     return;
12                 }
13                 document.body.innerHTML = "" + e.origin + "那里传来的消息." + "<br>" + e.data;
14                 //向主页面发送消息
15                 e.source.postMessage("你好,这里是" + this.location, e.origin);
16             },false);            
17         </script>
18     </body>
19 </html>

说明:

1. 通过对window对象的message事件进行监听,可以接收消息。

2. 通过访问message事件的origin属性,可以获取消息的发送源(发送源与网站的url地址不是同一概念,发送源只包括域名与端口号)。为了不接收从其他恶意源发送过来的消息,最好对发送源做个检查。

3. 通过访问message事件的data属性,可以取得消息内容。

4. 使用postMessage方法发送消息。

5. 通过访问message事件的source属性,可以获取消息发送源的窗口对象(准确的说,应该是窗口的代理对象)。

posted @ 2012-08-28 11:44  arinna  阅读(335)  评论(0)    收藏  举报