html5 postMessage解決跨域、跨視窗訊息傳遞

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   os   使用   java   ar   

問題:

對於跨域問題,研究了一下html5的postMessage,寫了代碼測試了一下,感覺html5新功能就是好用啊。
此文僅使用html5的新特性postMessage,示範其執行過程和效果:

方法解釋:
postMessage()方法允許來自不同源的指令碼採用非同步方式進行有限的通訊,可以實現跨文本檔、多視窗、跨域訊息傳遞。
postMessage(data,origin)方法接受兩個參數:
1.data:你需要傳遞的訊息,訊息傳遞的格式有一定要求:參數可以是JavaScript的任意基本類型或可複製的對象,然而並不是所有瀏覽器都做到了這點兒,部分瀏覽器只能處理字串參數,所以建議直接傳遞string型別參數。json格式使用JSON.stringify()方法對對象參數序列化,在低版本IE中引用json2.js可以實作類別似效果。
2.origin:該參數指明目標視窗的源。postMessage()方法只會將message傳遞給指定視窗,也可以設定為"*",表示可以傳遞給任意視窗。

原理:

1.我的頁面是parent.html,接收我發送的訊息並按照要求返回訊息的頁面是child.html;

2.兩個頁面放在同一個檔案夾內;

3.parent.html發送postMessage訊息給child.html,child.html收到訊息後通過source.postMessage返回所需資訊!

 

具體過程如下:

我的頁面是parent.html:

<html><div>    <iframe id="child" src="./child.html"></iframe></div><script type="text/javascript">    window.addEventListener(‘message‘,function(e){        alert("msg from child:" + e.data);    });    window.onload=function(){//頁面載入完即向iframe發送訊息        //var tmp = document.getElementById("child");        //tmp.postMessage(‘hello babi‘,‘*‘);  //此處tmp沒有postMessage方法,類型錯誤。        //alert(tmp); //這是object HTMLIFrameElement類型        //alert(window.frames[0]);  //這是object Window類型        //以上方式不可行,只有window類型才能調用postMessage方法!        window.frames[0].postMessage(‘hello babi‘,‘*‘);    }</script></html>

中間的文字全都來自child.html!

 

我們看看接收訊息頁面child.html:

parent頁面向child頁面發送了訊息,那麼在child頁面上如何接收訊息呢,監聽window的message事件就可以

<html><p id="ll">I‘m child</p><p id="ll">I‘m child</p><p id="ll">I‘m child</p><p id="ll">I‘m child</p><script type="text/javascript">    window.addEventListener(‘message‘,function(e){//接收資訊後返回資訊!        alert("msg from parent:" + e.data);        e.source.postMessage(‘Hello papi‘, "*");    });</script></html>

這樣我們就可以接收任何視窗傳遞來的訊息了!

我們運行一下:

這樣就實現了跨域、跨視窗訊息傳遞

 

html5 postMessage解決跨域、跨視窗訊息傳遞

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.