標籤: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>