首頁  >  文章  >  web前端  >  H5的window.postMessage與跨域

H5的window.postMessage與跨域

php中世界最好的语言
php中世界最好的语言原創
2018-03-26 16:18:282112瀏覽

這次帶給大家H5的window.postMessage與跨域,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('message', receiveMsg, false);
        }else {
            window.attachEvent('message', receiveMsg);
        }
    };

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

  1. ##data 傳送的特定訊息

  2. origin 發送訊息來源

  3. source 發送訊息視窗的window物件參考

##說明

    可以將postMessage函數第二個參數設為*,在傳送跨域訊息時會跳過對傳送訊息的來源的檢查。
  1. 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('btn');
                var btn_send = document.getElementById('send');
                var sendBtn = document.getElementById('sendMessage');
                var win;
                btn.onclick = function() {
                    //通过window.open打开接收消息目标窗口
                    win = window.open('http://jhssdemo.duapp.com/demo/h5_postmessage/win.html', 'popUp');
                }
                btn_send.onclick = function() { 
                    // 通过 postMessage 向子窗口发送数据      
                    win.postMessage('Hello', 'http://jhssdemo.duapp.com/');
                }
                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('txt');  
                //监听函数,接收一个参数--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('message', receiveMsg, false);
                }else {
                    window.attachEvent('message', receiveMsg);
                }
            };
        </script>
    </body>
    </html>

#相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

phonegap取得位置資訊詳解


phonegap建立聯絡人詳解

#

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

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