HTML5权威指南 11.通信API
生活随笔
收集整理的這篇文章主要介紹了
HTML5权威指南 11.通信API
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?
?
1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title></title> 7 <script type="text/javascript"> 8 //(1)監(jiān)聽message事件 9 window.addEventListener("message",function(ev){ 10 //(2)忽略指定URL地址之外的頁面?zhèn)鬟^來的消息 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)向主頁面發(fā)出消息 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 //向父頁面發(fā)送端口及消息 13 window.parent.postMessage("子頁面1已加載完畢", "http://localhost/test.html", [mc.port2]); 14 15 //定義本頁面中端口接收到消息時(shí)的事件處理函數(shù)中的內(nèi)容 16 portMessageHandler = function (portMsgEvent) { 17 alert(portMsgEvent.data); 18 } 19 20 //定義本頁面中端口接收到的消息時(shí)的事件處理函數(shù) 21 mc.port1.addEventListener("message", portMessageHandler, false); 22 23 //打開本頁面中的端口,開始監(jiān)聽 24 mc.port1.start(); 25 } 26 </script> 27 </head> 28 29 <body onload="window_onload();"> 30 31 </body> 32 33 </html>?
轉(zhuǎn)載于:https://www.cnblogs.com/wingzw/p/7446166.html
總結(jié)
以上是生活随笔為你收集整理的HTML5权威指南 11.通信API的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于网页数据导入excel问题
- 下一篇: 前端模块化(二):模块化编程