HTML5學習之跨文檔傳輸訊息(七)

來源:互聯網
上載者:User

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

新標準中提供了文檔之間直接的訊息傳輸API。而且不限制跨域訊息傳遞!發送訊息使用的是Window對象的postMessage(data,targetURL)方法就可以了,但給哪個window對象發送訊息,就使用哪個window的執行個體來調用,注意這個細節。文檔預設監聽一下message事件就可以接受訊息了:window.addEventListener("message", function (ev) {});監聽訊息事件:ev兩個重要屬性:ev.source指向發送訊息的源window對象,ev.data來擷取收到的訊息資料
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title></title>      <script>          window.onload = function() {              document.getElementById("btn").onclick = function() {                  document.getElementById("f").contentWindow.postMessage(document.getElementById("t").value, "*");              };          };    </script></head><body>    <input id="t" type="text" />    <input id="btn" type="button" />    <iframe id="f" src="receiveMsg.html" ></iframe></body></html>
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title></title>    <script type="text/javascript">        window.onmessage = function (event) {            //event.data  資料  event.origin 訊息來源地址  event.source   源DOMWindow 對象            alert(event.data);            alert(event.origin);            alert(event.source);        }    </script></head><body></body></html>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.