窗口之间通信类

通信方式有很多种:

  • ajax 不支持跨域通信(XMLHttpRequest2 其实标准的浏览器也是可支持跨域,只要后端设置一下头部也是可以跨域的,设置header(Access-Control-Allow-Origin: http://mywebdomain.com) 
  • webSocket  支持跨域通信
  • JSONP 支持跨域通信
  • PostMessage 支持跨域通信
  • CORS   支持跨域也支持同源, 是一个新的通信协议标准

 

跨域通信的几种方式
  • JSONP
  • Hash
  • postMessage
  • WebSocket
  • CORS
  • 借助Nginx/Apache 。。。

 

今天先来看下窗口之间的通信方式:

一般窗口通信分为三种:

1. iframe嵌套:多个iframe之间通信。

  1. 父页面操作子页面元素:oFrame.contentWindow.document.body。
  2. 父页面调用子页面方法:oFrame.contentWindow.functionName()。
  3. 子页面调用父页面元素: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可以实现跨域的窗口间的通信。
    以上内容欢迎大家提出疑问,有问题可以随意提出,共同进步,共同学习!!
posted @ 2018-04-24 12:48  Daya  阅读(1934)  评论(0编辑  收藏  举报