HTML5权威指南 11.通信API

 

 

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

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

 1 <!DOCTYPE html>
 2 <html>
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <title></title>
 7     <script type="text/javascript">
 8         function window_onload() {
 9             var mc, postMessageHandler;
10             mc = new MessageChannel();
11 
12             //向父页面发送端口及消息
13             window.parent.postMessage("子页面1已加载完毕", "http://localhost/test.html", [mc.port2]);
14 
15             //定义本页面中端口接收到消息时的事件处理函数中的内容
16             portMessageHandler = function (portMsgEvent) {
17                 alert(portMsgEvent.data);
18             }
19 
20             //定义本页面中端口接收到的消息时的事件处理函数
21             mc.port1.addEventListener("message", portMessageHandler, false);
22 
23             //打开本页面中的端口,开始监听
24             mc.port1.start();
25         }
26     </script>
27 </head>
28 
29 <body onload="window_onload();">
30 
31 </body>
32 
33 </html>

 

posted @ 2017-08-28 22:46  wingzw  阅读(191)  评论(0编辑  收藏  举报