postMessage和onmessage的使用
postMessage和onmessage是HTML5的方法,用來解決跨頁面通信,或者通過iframe嵌套的不同頁面的通信的。postMessage為發送方,onmessage為接收方。
注:該方法需要瀏覽器對 HTML5 的支持 查看是否支持...
一、發送方的代碼用法如下:
receiveWindow.postMessage(message, targetOrigin, [transfer]);
receiveWindow是接收方的window對象。可以通過以下幾種方法獲得,例如window.open()方法返回的值就是打開頁面的window對象,或者iframe元素的contentWindow屬性能獲得iframe標簽內頁面的window對象,等等。
參數說明:
message是你要發送到其他 window的數據。
targetOrigin是接收方域,可指定該值(一般為接收方頁面的window.origin),如果接收方窗口的協議、主機地址或端口這三者的任意一項不匹配targetOrigin提供的值,那么消息就不會被發送。該參數也可以是‘*’,表示對接收方的域沒有任何限制。
[transfer]是可選項,數組內的對象是實現Transferable接口的對象。它和message一樣會被傳遞給目標頁面,這些對象的所有權將被轉移給消息的接收方,而發送一方將不再保有所有權。
二、接收方監聽message事件,代碼方法如下:
window.onmessage = function(e){ }
參數e為message實例,里面包含了data、origin、source等屬性,data是發送方發送的message,origin是發送方所屬的域,source是發送方的window對象的引用。
示例:
A域(A項目)html代碼如下,里面嵌如B域頁面
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>a域頁面</title> <style> .myIframe { width: 500px; height: 300px; border: ridge; border-color: burlywood; margin: 15px 0 0 0; } button { color: #fff; background-color: #2d8cf0; border-color: #2d8cf0; border-radius: 4px; font-family: inherit; text-transform: none; display: inline-block; padding: 6px 15px; text-align: center; } </style> </head> <body> <div id="aaaaa"> <button onclick="send()">Send Message To Iframe</button> </div> <iframe id="proxy" class="myIframe" src="http://localhost:8081/spsarchive-webapp/web/zz/bbbbb.htm" ></iframe> <script type="text/javascript"> function send(){ var iframe= document.getElementById("proxy"); if (iframe){ //iframe.contentWindow.postMessage("AAAAA","*"); iframe.contentWindow.postMessage("AAAAA", "http://localhost:8081"); } } </script> </body> </html>
B域(B項目)頁面html代碼如下
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>b域頁面</title> <style> .btitle { text-align: center; margin-top: 10px; } .bclass { width: 100%; height: 100px; background-color: #3c536b4a; text-align: center; margin-top: 20px; } </style> </head> <body> <div id="bbbbb"> <div class="btitle"> <span>I am b page!</span> </div> <div id="bContent" class="bclass"> </div> </div> <script type="text/javascript"> window.onmessage = function(e){ console.info("received from A is: " + e.data); } </script> </body> </html>
特別說明:非原創,轉載:https://www.cnblogs.com/super-yu/p/9480589.html