iframe中子父頁面跨域通信


在非跨域的狀況下,iframe中的子父頁面能夠很方便的通信,可是在跨域的狀況下,只能經過window.postMessage()方法來向其餘頁面發送信息,其餘頁面要經過window.addEventListener()監聽事件來接收信息;html

#跨域發送信息

#window.postMessage()語法

otherWindow.postMessage(message, targetOrigin, [transfer]);
  • otherWindow
    其餘窗口的一個引用,寫的是你要通訊的window對象。
    例如:在iframe中向父窗口傳遞數據時,能夠寫成window.parent.postMessage(),window.parent表示父窗口。
  • message
    須要傳遞的數據,字符串或者對象均可以。
  • targetOrigin
    表示目標窗口的源,協議+域名+端口號,若是設置爲「*」,則表示能夠傳遞給任意窗口。在發送消息的時候,若是目標窗口的協議、域名或端口這三者的任意一項不匹配targetOrigin提供的值,那麼消息就不會被髮送;只有三者徹底匹配,消息纔會被髮送。例如:
    window.parent.postMessage('hello world','http://xxx.com:8080/index.html')
    只有父窗口是http://xxx.com:8080時纔會接受到傳遞的消息。java

  • [transfer]
    可選參數。是一串和message 同時傳遞的 Transferable 對象,這些對象的全部權將被轉移給消息的接收方,而發送一方將再也不保有全部權。咱們通常不多用到。跨域

#跨域接收信息

須要監聽的事件名爲"message"bash

window.addEventListener('message', function (e) {
    console.log(e.data)  //e.data爲傳遞過來的數據
    console.log(e.origin)  //e.origin爲調用 postMessage 時消息發送方窗口的 origin(域名、協議和端口)
    console.log(e.source)  //e.source爲對發送消息的窗口對象的引用,可使用此來在具備不一樣origin的兩個窗口之間創建雙向通訊
})

#示例Demo

示例功能:跨域狀況下,子父頁面互發信息並接收。post

  • 父頁面代碼:
<body>
    <button onClick="sendInfo()">向子窗口發送消息</button>
    <iframe id="sonIframe" src="http://192.168.2.235/son.html"></iframe>
    <script type="text/javascript">

        var info = {
            message: "Hello Son!"
        };
        //發送跨域信息
        function sendInfo(){
            var sonIframe= document.getElementById("sonIframe");
            sonIframe.contentWindow.postMessage(info, '*');
        }
        //接收跨域信息
        window.addEventListener('message', function(e){
                alert(e.data.message);
        }, false);
    </script>
</body>
  • 子頁面代碼
<body>
    <button onClick="sendInfo()">向父窗口發送消息</button>
    <script type="text/javascript">

        var info = {
            message: "Hello Parent!"
        };
        //發送跨域信息
        function sendInfo(){
            window.parent.postMessage(info, '*');
        }
        //接收跨域信息
        window.addEventListener('message', function(e){
                alert(e.data.message);
        }, false);
    </script>
</body>
相關文章
相關標籤/搜索