iframe(3) ---親ページと子ページは相互に値を渡します

最終的な効果は以下の通り

  1. 親ページのボタンをクリックして値を子ページに渡します
    ここに画像の説明を挿入します

2. サブページ ボタンをクリックして値を親ページに渡します
ここに画像の説明を挿入します

コードは以下のように表示されます。

親ページ

<!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>
    <h2>我是父页面:</h2>
    <div style="display: flex; flex-direction: column; align-items: flex-start">
      <button onclick="handleMessage()">发送给子组件</button>
      <iframe
        src="http://192.168.10.68:9997/iframe/zi.html"
        frameborder="0"
        id="tempId"
      ></iframe>
    </div>
    <script>
      var docHeight = 0;
      function handleMessage(e) {
    
    
        // 写法一
        let target = document.getElementById("tempId");
        target.contentWindow.postMessage(
          "传递给子页面的数据",
          "http://192.168.10.68:9997/iframe/zi.html"
        );

        // 写法二
        // let target = window.frames[0];
        // target.postMessage(
        //   "传递给子页面的数据",
        //   "http://192.168.10.68:9998/iframe/zi.html"
        // );
      }

      // 接收子页面发送的message信息
      window.addEventListener("message", (data) => {
    
    
        console.log("接收来自子页面,", data);
      });
    </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>
    <button onclick="handleMessage()">发送给父页面</button>
    <script>
      function handleMessage(e) {
    
    
        let target = document.getElementById("tempId");
        window.parent.postMessage("传递给父页面的内容", "*");
      }

      // 接收父页面发送的message信息
      window.addEventListener("message", (data) => {
    
    
        console.log("接收来自父页面,", data);
      });
    </script>
  </body>
</html>

おすすめ

転載: blog.csdn.net/u013558749/article/details/129622227