標籤:

HTML5 postMessage

在HTML5中新增了postMessage方法,postMessage可以實現跨文檔消息傳輸(Cross Document Messaging),Internet Explorer 8, Firefox 3, Opera 9, Chrome 3和 Safari 4都支持postMessage。

  可以通過綁定window的message事件來監聽發送跨文檔消息傳輸內容。示例代碼如下:

eg.) parent page

Html代碼

  1. <span style="font-size: small;"><!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <title>Communication</title>
  5. <script>
  6. var messageChange = function(e) {
  7. var data = e.data;
  8. var origin = e.origin;
  9. if (origin !== "http://www.example.org") return;
  10. document.getElementById("display").innerHTML = data;
  11. };
  12. if (typeof window.addEventListener != "undefined") {
  13. window.addEventListener("message", messageChange, false);
  14. } else if (typeof window.attachEvent != "undefined") {
  15. window.attachEvent("onmessage", messageChange);
  16. }
  17. </script>
  18. </head>
  19. <body>
  20. <div id="display">Say something!</div>
  21. <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>
  22. </body>
  23. </html>
  24. </span>
  25. <span style="font-size: small;">
  26. </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代碼

  1. <span style="font-size: small;"><!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <title>Communication</title>
  5. <script>
  6. setInterval(function(){
  7. window.parent.postMessage("hello world!", "http://www.example.org");
  8. },1000);
  9. </script>
  10. </head>
  11. <body></body>
  12. </html></span>
  13. <span style="font-size: small;">
  14. </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基礎一

TAG:HTML5 | HTML |