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>
相关文章
相关标签/搜索