首頁  >  文章  >  web前端  >  HTML5 window.postMessage與跨網域的實例教學

HTML5 window.postMessage與跨網域的實例教學

零下一度
零下一度原創
2017-05-13 13:14:361601瀏覽

這篇文章主要介紹了詳解HTML5 window.postMessage與跨域,非常具有實用價值,需要的朋友可以參考下

在前一篇文章中,講到瀏覽器同源策略,即阻止不同域的頁間存取彼此的方法和屬性,並對解決同源策略跨域問題提出的解決方案進行闡述:子域代理、JSONP、CORS。本篇將詳細說明HTML5 window.postMessage,借助postMessage API,文檔間可以以安全可控的方式實現跨域通信,第三方JavaScript程式碼也可以與iframe內載入的外部文檔進行通信。

HTML5 window.postMessage API

#HTML5 window.postMessage是一個安全的、基於事件的訊息API。

postMessage傳送訊息

在需要傳送訊息的來源視窗呼叫postMessage方法即可傳送訊息。

來源視窗

來源視窗可以是全域的window對象,也可以是下列類型的視窗:

文件視窗中的iframe:  

var iframe = document.getElementById('my-iframe');
    var win = iframe.documentWindow;

JavaScript開啟的彈跳視窗:  

var win = window.open();

目前文件視窗的父視窗:  

var win = window.parent;

開啟目前文件的視窗:  

var win = window.opener();

找到來源window物件之後,即可呼叫postMessage API向目標視窗發送訊息:

``win.postMessage('Hello', 'ttp://jhssdemo.duapp.com/');"

postMessage函數接收兩個參數:第一個為將要傳送的訊息,第二個為來源視窗的來源。

註:只有當目標視窗的來源與postMessage函數中傳入的來源參數值相符時,才能接收到訊息。

接收postMessage訊息

要想接收到先前來源視窗透過postMessage發出的訊息,只需要在目標視窗註冊message事件並綁定事件監聽函數,就可以在函數參數中取得訊息。


window.onload = function() {
        var text = document.getElementById('txt');  
        function receiveMsg(e) {
            console.log("Got a message!");
            console.log("nMessage: " + e.data);
            console.log("nOrigin: " + e.origin);
            // console.log("Source: " + e.source);
            text.innerHTML = "Got a message!<br>" +
                "Message: " + e.data +
                "<br>Origin: " + e.origin;
        }
        if (window.addEventListener) {
            //为窗口注册message事件,并绑定监听函数
            window.addEventListener(&#39;message&#39;, receiveMsg, false);
        }else {
            window.attachEvent(&#39;message&#39;, receiveMsg);
        }
    };

message事件監聽函數接收一個參數,Event物件實例,該物件有三個屬性:

  1. data 傳送的具體訊息

  2. origin 發送訊息來源

  3. source 發送訊息視窗的window物件引用

說明

  1. 可以將postMessage函數第二個參數設為*,在傳送跨域訊息時會跳過對傳送訊息的來源的檢查。

  2. postMessage只能傳送字串訊息。

實例

#來源視窗 

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Html5 postMessage</title>
        <style>
            #otherWin {
                width: 600px;
                height: 400px;
                background-color: #cccccc;
            }
        </style>
    </head>
    <body>
        <button id="btn">open</button>
        <button id="send">send</button>
         <!-- 通过 iframe 嵌入子页面(接收消息目标窗口) --> 
         <iframe src="http://jhssdemo.duapp.com/demo/h5_postmessage/win.html" 
                     id="otherWin"></iframe> 
         <br/><br/> 
         <input type="text" id="message"><input type="button" 
                 value="Send to child.com" id="sendMessage" /> 
        <script>
            window.onload = function() {
                var btn = document.getElementById(&#39;btn&#39;);
                var btn_send = document.getElementById(&#39;send&#39;);
                var sendBtn = document.getElementById(&#39;sendMessage&#39;);
                var win;
                btn.onclick = function() {
                    //通过window.open打开接收消息目标窗口
                    win = window.open(&#39;http://jhssdemo.duapp.com/demo/h5_postmessage/win.html&#39;, &#39;popUp&#39;);
                }
                btn_send.onclick = function() { 
                    // 通过 postMessage 向子窗口发送数据      
                    win.postMessage(&#39;Hello&#39;, &#39;http://jhssdemo.duapp.com/&#39;);
                }
                function sendIt(e){ 
                    // 通过 postMessage 向子窗口发送数据
                    document.getElementById("otherWin").contentWindow 
                    .postMessage( 
                        document.getElementById("message").value, 
                        "http://jhssdemo.duapp.com/"); 
                } 
                sendBtn.onclick = function(e) {
                    sendIt(e);
                };
            };
        </script>
    </body>
    </html>

目標視窗win.html

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Html5 postMessage</title>
        <style>
            #txt {
                width: 500px;
                height: 300px;
                background-color: #cccccc;
            }
        </style>
    </head>
    <body>
        <h1>The New Window</h1>
        <p id="txt"></p>
        <script>        
            window.onload = function() {
                var text = document.getElementById(&#39;txt&#39;);  
                //监听函数,接收一个参数--Event事件对象
                function receiveMsg(e) {
                    console.log("Got a message!");
                    console.log("nMessage: " + e.data);
                    console.log("nOrigin: " + e.origin);
                    text.innerHTML = "Got a message!<br>" +
                        "Message: " + e.data +
                        "<br>Origin: " + e.origin;
                }
                if (window.addEventListener) {
                    //为window注册message事件并绑定监听函数
                    window.addEventListener(&#39;message&#39;, receiveMsg, false);
                }else {
                    window.attachEvent(&#39;message&#39;, receiveMsg);
                }
            };
        </script>
    </body>
    </html>

#回顧

透過本篇的學習,了解了使用HTML5的postMessage API在視窗間進行通信,也知道可以藉助其實現跨域通信;現代瀏覽器基本上都支持postMessage,而對於一些老式瀏覽器如IE7-等,可以使用一定的替代方案,進行資料通信,如window.name、url查詢字元和hash片段等。

【相關推薦】

1. 特別推薦「php程式設計師工具箱」V0.1版本下載

2. 免費h5線上影片教學

#3. php.cn原始html5影片教學

#########

以上是HTML5 window.postMessage與跨網域的實例教學的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn