iframe页面之间通信

父页面:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button onclick="addClick()">發送消息</button>
    <iframe
      src="http://localhost:9008/iframeTest/"
      id="testIframework"
    ></iframe>
    <script>
      function addClick() {
        let dom = document.querySelector("#testIframework");
        dom.contentWindow.postMessage(
          { a: "q2w3qwe" },
          "*"
        );
      }
    </script>
  </body>
</html>

子页面:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    這是一個子頁面
    <span id="msgContnet"></span>
    <script>
      // document.getElementById('msgContnet').innerText
      window.onload = function () {
        window.addEventListener("message", function(data){
          debugger;
        });
      };
    </script>
  </body>
</html>
积累小的知识,才能成就大的智慧,希望网上少一些复制多一些原创有用的答案
原文地址:https://www.cnblogs.com/llcdbk/p/15248726.html