> For the complete documentation index, see [llms.txt](https://jen-hsuan-hsieh.gitbook.io/javascript-node-js/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jen-hsuan-hsieh.gitbook.io/javascript-node-js/chapter1/11bi-ji/19iframe/19iframe-communication.md).

# 1.9.1.IFrame communication

## 1.Introduction

* 讓iframe發送訊息給parent (iframe是發送訊息的一方, parent是接收訊息的一方)
* HTML5的postMessage可在不同網頁間送資料, 可以使用window\.open開啟另一網域的資料將文字訊息傳過去, 或是使用contentWindow取得IFrame載入的頁面

## 2.Implementation

* 1.在不同網頁間傳遞訊息
  * parent (傳訊息)

    ```
      <script>
          var new_win;

          /* 開啟另一個網頁 */
          function openWin() {
              new_win = window.open("http://demo2.cinc.biz/html5-postmessage/text-new.html");
          }

          /* 傳送文字訊息 */
          function sendMsg() {
              var msg = document.getElementById("msg_txt").value;
              new_win.postMessage(msg, "http://demo2.cinc.biz");//表示要送給demo2.example.com網域
          }
      </script>
    ```
  * IFrame (收訊息)

    ```
      <script>
          var myMsg = function(e) {
              alert("接收到的訊息：" + e.data);
              alert("訊息來源網域：" + e.origin);
              if (e.origin != "http://demo.cinc.biz") {
                  alert("不明來源,不處理");
                  return; //不明來源,不處理
              }

              document.getElementById("res").innerHTML = "接收到的訊息：" + e.data;
          };
          window.addEventListener("message", myMsg, false);//監聽message事件
      </script>
    ```
* 2.IFrame傳訊息給parent
  * parent (傳/收訊息)

    ```
    <script>
      // Create the iframe
      var iframe = document.createElement('iframe');
      iframe.setAttribute('src', iframeSource);
      iframe.setAttribute('id', 'the_iframe');
      iframe.style.width = 450 + 'px';
      iframe.style.height = 200 + 'px';
      document.body.appendChild(iframe);
      // Send a message to the child iframe
      var iframeEl = document.getElementById('the_iframe'),
          messageButton = document.getElementById('message_button'),
          results = document.getElementById('results');
      // Send a message to the child iframe
      var sendMessage = function(msg) {
          // Make sure you are sending a string, and to stringify JSON
          iframeEl.contentWindow.postMessage(msg, '*');
      };
      // Send random messge data on every button click
      bindEvent(messageButton, 'click', function (e) {
          var random = Math.random();
          sendMessage('' + random);
      });
      // Listen to message from child window
      bindEvent(window, 'message', function (e) {
          results.innerHTML = e.data;
      });
    </script>
    ```
  * IFrame (傳/收訊息)

    ```
    <script>
      // addEventListener support for IE8
      function bindEvent(element, eventName, eventHandler) {
          if (element.addEventListener) {
              element.addEventListener(eventName, eventHandler, false);
          } else if (element.attachEvent) {
              element.attachEvent('on' + eventName, eventHandler);
          }
      }
      // Send a message to the parent
      var sendMessage = function (msg) {
          // Make sure you are sending a string, and to stringify JSON
          window.parent.postMessage(msg, '*');
      };
      var results = document.getElementById('results'),
          messageButton = document.getElementById('message_button');
      // Listen to messages from parent window
      bindEvent(window, 'message', function (e) {
          results.innerHTML = e.data;
      });
      // Send random message data on every button click
      bindEvent(messageButton, 'click', function (e) {
          var random = Math.random();
          sendMessage('' + random);
      });
    </script>
    ```

## 3.Reference

* <http://xyz.cinc.biz/2014/05/html5-postmessage-text.html>
* <https://github.com/pbojinov/iframe-communication/blob/master/iframe.html>
