html5的postmessage實現js前端跨域訪問及調用解決方式


關於跨域訪問。使用JSONP的方法。我前面已經demo過了。詳細見http://supercharles888.blog.51cto.com/609344/856886,HTML5提供了一個很強大的API。叫postMessage。它事實上就是曾經iframe的進化版本號,使用起來極其方便,這里舉個實驗樣例:

我們依然依照與上文同樣的設定。假定我們有2個Domain

Domain1: http://localhost:8080  它上面有個應用叫HTMLDomain1,而且有個頁面叫sender.html。

Domain2:http://localhost:8180 它上面有個應用叫HTMLDomain2,而且有個頁面叫receiver.html。

我如今的需求是。假定Domain1上我們有個json數據,我們想讓Domain2應用中的javascript要能夠操作這個json 數據(注意。這里已經是跨域了,由於Domain2上的js操作了Domain1上的數據)。應該怎么辦呢?

解決方式就是用HTML5的postMessage方法

Domain2的代碼:

首先。我們在Domain2上創建一個HTML頁面,這個頁面沒什么內容。就一行文字會來標識它是Domain 2,它下方將來會被js用來填充從Domain1弄過來的數據。

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="UTF-8"> 
<title>Domain2上的接收者頁面receiver.html</title> 
<script type="text/javascript" src="js/receiveInfo.js"></script> 
</head> 
<body onload="receiveInfoFromAnotherDomain();"> 
     
     
<p>這個頁面是HTML5跨域訪問的Domain2上的頁面receiver.html,它會處理來自Domain1上sender.html發送的頁面</p> 
     
     
</body> 
</html>

Domain2頁面載入時候,它會調用receiveInfoFromAnotherDomain()函數。這個函數首先定義了一個事件監聽函數,它僅僅接受來自Domain1(http://localhost:8080)的事件,否則就忽略掉,然后它從這個事件中分離出信息負載,也就是json 數據。然后顯示在頁面底部:

//這個函數用於處理從Domain1上的sender發送過來的信息,然后將他們打印出來 
function receiveInfoFromAnotherDomain(){ 
         
    console.log("entering method receiveInfoFromAnotherDomain()"); 
    //首先讓window加入一個事件監聽函數,表明它能夠監聽窗體對象的message事件 
    //它受到事件時,會先推斷是否來自指定的Domain(不是全部Domain丟過來的事件它都處理的) 
    window.addEventListener("message",function(ev){ 
        console.log("the receiver callback func has been invoked"); 
             
        //假設不是來自指定Domain的,則忽略 
        if(ev.origin !="http://localhost:8080"){ 
            console.log("the event doesn't come from Domain1!"); 
            return; 
        } 
             
        //如今能夠處理數據了 
        //控制台打印出接收到的json數據,由於我們把json字符串發送了過來 
        console.log(ev.data); 
     
        //將json字符串轉為json對象。然后從中分離出原始信息 
        var personInfoJSON = JSON.parse(ev.data); 
        var name = personInfoJSON.name; 
        var title = personInfoJSON.title; 
        var info = personInfoJSON.info; 
             
        //構造信息文本而且顯示在頁面的底部 
        var personInfoString="從域為: "+ev.origin+"那里傳來的數據."+"<br>"; 
        personInfoString+="姓名是: "+name+"<br>"; 
        personInfoString+="頭銜為:  "+title+"<br>"; 
        personInfoString+="信息為:  "+info+"<br>"; 
        document.body.innerHTML=personInfoString; 
                     
        } 
             
    ); 
     
     
     
     
}

然后將Domain2 (http://localhost:8180)啟動起來,不出意外。它將是:

Domain1的代碼:

如今,我們來構建Domain1:

為了讓Domain1可以和Domain2通過事件交互,我們用了iframe,把Domain2的頁面receiver.html以<iframe>形式鑲嵌在Domain1的sender.html頁面中。

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="UTF-8"> 
<title>Domain1上的發送者頁面sender.html</title> 
<script type="text/javascript" src="js/sendInfo.js"></script> 
</head> 
<body> 
     
<p>這個頁面是HTML5跨域訪問的Domain1上的頁面sender.html。它將發送一些信息到Domain2上的receiver.html</p> 
<input type="button" value="點擊則發送事件到Domain2" onclick="sendInfoToAnotherDomain();"/> 
     
<!-- 這個iframe包括了在另外一個domain->Domain2(http://localhost:8180)的接收者頁面receiver.html -->
<iframe width="1200" src="http://localhost:8180/HTML5Domain2/receiver.html"></iframe> 
</body> 
</html>

同一時候我們在頁面上創建一個button,當點擊它就會發送json數據給Domain2.

所以js函數就負責以json字符串形式發送json數據。然后讓iframe中的Domain2頁面發送信息,注意這里接受者的窗體在iframe中,所以我們用iframe.postMessage,第一個參數是我們的信息載體。這里是json字符串,第二個參數是目標Domain,也就是Domain2

//假定這個Domain(Domain1)要把一些json信息發送到還有一個域(Domain2)的某個頁面 
function sendInfoToAnotherDomain(){ 
         
    console.log("entering method: sendInfoToAnotherDomain()"); 
         
    //首先構造一個對象,內含有我們想要發送到Domain2的信息,然后把它轉為json字符串    
    var personInfo= new Object; 
    personInfo.name='charles'; 
    personInfo.title='technical lead'; 
    personInfo.info="talent man"; 
    var str=JSON.stringify(personInfo); 
         
    console.log("The information to be send: "+str); 
         
    //我們把這個json字符串發送到Domain2 
    //由於這個Domain2上的目標頁面被嵌在了主頁面上作為iframe,所以我們取得這個iframe然后讓他來發送信息 
    //信息的內容是我們的包括個人信息內容的json字符串 
    var iframe=window.frames[0];     
    iframe.postMessage(str,'http://localhost:8180'); 
         
    console.log("json string has been sent to domain2 successfully"); 
}

這樣一來,我們就定義了發送者(Domain1)和接收者(Domain2),發送者因為嵌了<iframe>所以頁面看上去例如以下圖:

當點擊"點擊則發送事件到Domain2" button后,json數據信息被發送到了Domain2,由於Domain2的事件監聽程序注冊了監聽來自Domain1的事件,所以它能夠把事件中攜帶的json字符串解析成原始信息,然后構造文本顯示在Domain2的receiver.html的下方。如圖:(能夠比照sendInfoToAnotherDomain()。能夠發現信息是全然匹配的)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM