HTML5 postMessage
可以通過綁定window的message事件來監聽發送跨文檔消息傳輸內容。示例代碼如下:
eg.) parent page
Html代碼
- <span style="font-size: small;"><!DOCTYPE HTML>
- <html>
- <head>
- <title>Communication</title>
- <script>
- var messageChange = function(e) {
- var data = e.data;
- var origin = e.origin;
- if (origin !== "http://www.example.org") return;
- document.getElementById("display").innerHTML = data;
- };
- if (typeof window.addEventListener != "undefined") {
- window.addEventListener("message", messageChange, false);
- } else if (typeof window.attachEvent != "undefined") {
- window.attachEvent("onmessage", messageChange);
- }
- </script>
- </head>
- <body>
- <div id="display">Say something!</div>
- <iframe scrolling="no" frameborder="0" width_="0" height="0" src="https://www.getit01.com/getimg_360.php?url=http://www.example.org/html5/postMessage/sub.html"></iframe>
- </body>
- </html>
- </span>
- <span style="font-size: small;">
- </span>
<!DOCTYPE HTML><html><head><title>Communication</title><script>var messageChange = function(e) {var data = e.data;var origin = e.origin;if (origin !== "http://www.example.org") return;document.getElementById("display").innerHTML = data;};if (typeof window.addEventListener != "undefined") {window.addEventListener("message", messageChange, false);} else if (typeof window.attachEvent != "undefined") {window.attachEvent("onmessage", messageChange);}</script></head><body><div id="display">Say something!</div><iframe scrolling="no" frameborder="0" width_="0" height="0" src="https://www.getit01.com/getimg_360.php?url=http://www.example.org/html5/postMessage/sub.html"></iframe></body></html>
eg.) sob page
Html代碼
- <span style="font-size: small;"><!DOCTYPE HTML>
- <html>
- <head>
- <title>Communication</title>
- <script>
- setInterval(function(){
- window.parent.postMessage("hello world!", "http://www.example.org");
- },1000);
- </script>
- </head>
- <body></body>
- </html></span>
- <span style="font-size: small;">
- </span>
<!DOCTYPE HTML><html><head><title>Communication</title><script>setInterval(function(){window.parent.postMessage("hello world!", "http://www.example.org");},1000);</script></head><body></body></html>
DEMO見附件, 更多HTML5相關demo地址:http://html5demos.com/
推薦閱讀:
※HTML元素有什麼優勢,而我從頭到尾就會用個div??
※靜態 HTML 文件怎麼從外部調入 HTML 模板(如頭部,頁尾這些公共的部分)?
※淺析瀏覽器輸入URL到頁面輸出執行流程
※請問如何從頭開始學習製作一款HTML5 小遊戲?
※html5基礎一