窗口之間通信類
阿新 • • 發佈:2018-04-24
來看 info .html ide HA 1-43 button htm str
通信方式有很多種:
- ajax 不支持跨域通信
- webSocket 支持跨域通信
- CORS 支持跨域也支持同源, 是一個新的通信協議標準
跨域通信的幾種方式
- JSONP
- Hash
- postMessage
- WebSocket
- CORS
今天先來看下窗口間的通信方式。
一般窗口通信分為三種:
- iframe嵌套:多個iframe之間通信。
- 父頁面操作子頁面元素:oFrame.contentWindow.document.body。
- 父頁面調用子頁面方法:oFrame.contentWindow.functionName()。
- 子頁面調用父頁面元素:window.top/parent/window
- 用window.open()方法打開一個新的窗口。
- 父頁面操作子頁面元素:window.open()打開子頁面時,返回子頁面窗口對象。
- 子頁面操作父頁面元素:window.opener即為父窗口對象。
- html5t提供的postMessage方法和message事件。(可以跨域通信)
- postMessage():接收消息窗口對象.postMessage("發送的數據","接收的域"); 這裏的域一定要帶上協議
- message事件:接收消息窗口監聽message事件,事件對象中包含有origin屬性和data屬性。其中ev.origin可以獲取發送數據的域,ev.data獲取發送的具體數據。
-
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <iframe id="myFrame" src="http://localhost:63342/XChart/Iframe2.html" width="600px;"></iframe
postMessage1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <p>http://localhost:63342/XChart/Iframe2.html</p> 9 </body> 10 </html> 11 <script type="text/javascript"> 12 window.onload = function(){ 13 window.addEventListener("message",function(ev){ 14 alert("父窗口向子窗口發送的數據是:" + ev.data); 15 alert("數據來源是:" + ev.origin); 16 }) 17 } 18 19 </script>
View Code
- 其中postMessage和Message可以實現跨域的窗口間的通信。
- 以上內容歡迎大家提出疑問,有問題可以隨意提出,共同進步!!
窗口之間通信類