1. 程式人生 > >窗口之間通信類

窗口之間通信類

來看 info .html ide HA 1-43 button htm str

通信方式有很多種:

  • ajax 不支持跨域通信
  • webSocket 支持跨域通信
  • CORS 支持跨域也支持同源, 是一個新的通信協議標準

跨域通信的幾種方式
  • JSONP
  • Hash
  • postMessage
  • WebSocket
  • CORS

今天先來看下窗口間的通信方式。

一般窗口通信分為三種:

  1. iframe嵌套:多個iframe之間通信。
    • 父頁面操作子頁面元素:oFrame.contentWindow.document.body。
    • 父頁面調用子頁面方法:oFrame.contentWindow.functionName()。
    • 子頁面調用父頁面元素:window.top/parent/window
    • 技術分享圖片
  2. 用window.open()方法打開一個新的窗口。
    • 父頁面操作子頁面元素:window.open()打開子頁面時,返回子頁面窗口對象。
    • 子頁面操作父頁面元素:window.opener即為父窗口對象。
  3. 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
      ><br /> 9 <input type="button" value="向子窗口發送數據" id="btn" /> 10 </body> 11 </html> 12 <script type="text/javascript"> 13 window.onload = function(){ 14 var myFrame = document.getElementById("myFrame"); 15 var oBtn = document.getElementById("btn"); 16 17 oBtn.onclick = function(){ 18 myFrame.contentWindow.postMessage("testData","http://localhost:63342"); 19 } 20 } 21 function parentWindowHandler(){ 22 alert("這是父窗口的方法,可以被子窗口調用"); 23 } 24 </script>
      postMessage 技術分享圖片
       1 <!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可以實現跨域的窗口間的通信。
    以上內容歡迎大家提出疑問,有問題可以隨意提出,共同進步!!

窗口之間通信類