主頁 > 知識(shí)庫 > 詳解HTML5 window.postMessage與跨域

詳解HTML5 window.postMessage與跨域

熱門標(biāo)簽:硅谷的囚徒呼叫中心 網(wǎng)站建設(shè) 使用U盤裝系統(tǒng) 檢查注冊表項(xiàng) 美圖手機(jī) 阿里云 智能手機(jī) 百度競價(jià)點(diǎn)擊價(jià)格的計(jì)算公式

在前一篇文章中,講到瀏覽器同源策略,即阻止不同域的頁面間訪問彼此的方法和屬性,并對解決同源策略跨域問題提出的解決方案進(jìn)行闡述:子域代理、JSONP、CORS。本篇將詳細(xì)闡述HTML5 window.postMessage,借助postMessage API,文檔間可以以安全可控的方式實(shí)現(xiàn)跨域通信,第三方JavaScript代碼也可以與iframe內(nèi)加載的外部文檔進(jìn)行通信。

HTML5 window.postMessage API

HTML5 window.postMessage是一個(gè)安全的、基于事件的消息API。

postMessage發(fā)送消息

在需要發(fā)送消息的源窗口調(diào)用postMessage方法即可發(fā)送消息。

源窗口

源窗口可以是全局的window對象,也可以是以下類型的窗口:

文檔窗口中的iframe:  

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

JavaScript打開的彈窗:  

var win = window.open();

當(dāng)前文檔窗口的父窗口:  

var win = window.parent;

打開當(dāng)前文檔的窗口:  

var win = window.opener();

找到源window對象后,即可調(diào)用postMessage API向目標(biāo)窗口發(fā)送消息:

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

postMessage函數(shù)接收兩個(gè)參數(shù):第一個(gè)為將要發(fā)送的消息,第二個(gè)為源窗口的源。

注:只有當(dāng)目標(biāo)窗口的源與postMessage函數(shù)中傳入的源參數(shù)值匹配時(shí),才能接收到消息。

接收postMessage消息

要想接收到之前源窗口通過postMessage發(fā)出的消息,只需要在目標(biāo)窗口注冊message事件并綁定事件監(jiān)聽函數(shù),就可以在函數(shù)參數(shù)中獲取消息。

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事件,并綁定監(jiān)聽函數(shù)
            window.addEventListener('message', receiveMsg, false);
        }else {
            window.attachEvent('message', receiveMsg);
        }
    };

message事件監(jiān)聽函數(shù)接收一個(gè)參數(shù),Event對象實(shí)例,該對象有三個(gè)屬性:

  1. data 發(fā)送的具體消息
  2. origin 發(fā)送消息源
  3. source 發(fā)送消息窗口的window對象引用

說明

  1. 可以將postMessage函數(shù)第二個(gè)參數(shù)設(shè)為*,在發(fā)送跨域消息時(shí)會(huì)跳過對發(fā)送消息的源的檢查。
  2. postMessage只能發(fā)送字符串信息。

實(shí)例

源窗口  

<!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 嵌入子頁面(接收消息目標(biāo)窗口) --> 
         <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打開接收消息目標(biāo)窗口
                    win = window.open('http://jhssdemo.duapp.com/demo/h5_postmessage/win.html', 'popUp');
                }
                btn_send.onclick = function() { 
                    // 通過 postMessage 向子窗口發(fā)送數(shù)據(jù)      
                    win.postMessage('Hello', 'http://jhssdemo.duapp.com/');
                }
                function sendIt(e){ 
                    // 通過 postMessage 向子窗口發(fā)送數(shù)據(jù)
                    document.getElementById("otherWin").contentWindow 
                    .postMessage( 
                        document.getElementById("message").value, 
                        "http://jhssdemo.duapp.com/"); 
                } 
                sendBtn.onclick = function(e) {
                    sendIt(e);
                };
            };
        </script>
    </body>
    </html>

目標(biāo)窗口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>
        <div id="txt"></div>
        <script>        
            window.onload = function() {
                var text = document.getElementById('txt');  
                //監(jiān)聽函數(shù),接收一個(gè)參數(shù)--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事件并綁定監(jiān)聽函數(shù)
                    window.addEventListener('message', receiveMsg, false);
                }else {
                    window.attachEvent('message', receiveMsg);
                }
            };
        </script>
    </body>
    </html>

回顧

通過本篇的學(xué)習(xí),了解了使用HTML5的postMessage API在窗口間進(jìn)行通信,也知道可以借助其實(shí)現(xiàn)跨域通信;現(xiàn)代瀏覽器基本都支持postMessage,而對于一些老式瀏覽器如IE7-等,可以使用一定的替代方案,進(jìn)行數(shù)據(jù)通信,如window.name、url查詢字符和hash片段等。  

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

標(biāo)簽:通遼 黃山 煙臺(tái) 湖北 湘潭 賀州 懷化 山南

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《詳解HTML5 window.postMessage與跨域》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266