iframe과 부모창간의 메시지 통신예제입니다.

 

 

 

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Main</title>
    <style>
      html,
      body {
        width: 100%;
        height: 100%;
      }
      textarea {
        border: 1px solid #ccc;
        box-sizing: border-box;
        width: 100%;
        resize: none;
        height: 30vh;
        padding: 1em;
      }
      textarea:focus {
        outline: none;
      }
    </style>
  </head>
  <body>
    <iframe src="chart.html" width="100%" height="300"></iframe>
    <textarea id="log"></textarea>
    <script>
      window.addEventListener("message", (event) => {
        // if (event.origin !== "https://parent-origin.com") {
        //   return;
        // }

        const logElement = document.getElementById("log");
        const message = event.data;
        if (message.type !== "chart") return;
        logElement.textContent += JSON.stringify(message) + "\r\n";
        logElement.scrollTop = logElement.scrollHeight; //스크롤 내리기
      });
    </script>
  </body>
</html>

 

 

chart.html

<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Chart</title>
    <style>
      html,
      body {
        width: 100%;
        height: 100%;
        background-color: #ccc;
        overflow: hidden;
      }
    </style>
  </head>
  <body>
    CHART
    <br />
    <button type="button" onclick="sendMessage(event)">이벤트 전송</button>
    <br />
    <script>
      function sendMessage(event) {
        const message = {
          type: "chart",
          time: new Date(),
          text: "Message from chart",
          data: [0, 1, 2, 3],
        };
        window.parent.postMessage(message, "*");
      }
    </script>
  </body>
</html>

 

 

소스 다운

iframe_event.zip
0.00MB

+ Recent posts