iframe 引用传参

父页面

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>iframe父级页面</title>
  <style>
    * {
      padding: 0;
      margin: 0;
    }

    iframe {
      width: 200px;
      height: 200px;
    }
  </style>

</head>

<body>
  <h2>我是父级页面</h2>
  <button id='btn'>父页面的按钮</button>
  <div id="default">div内容</div>
  <iframe src="http://127.0.0.1:5500/child.html" frameborder="0" name='myframe' id='myframe'></iframe>
  <script language="javascript" type="text/javascript">
  /* 监听子页面事件 */
    window.addEventListener('message', function (e) {
      console.log(e.data, '父页面输出');
      if (e.data.msg === 'hideselfService') {
        document.getElementById('default').style.display = 'none';
      }
    });
    
    document.getElementById('btn').onclick = function () {
      /* 向子页面发送数据 */
      var myframe = document.getElementById('myframe');
      myframe.contentWindow.postMessage({ data: 'parent' }, '*');
    }
  </script>
</body>

</html>

子页面

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>iframe子页面</title>
</head>

<body>
  <h2>我是内嵌的子页面</h2>
  <button id='btn'>子页面的按钮</button>
  <script>
    document.getElementById('btn').onclick = function () {
      /* 向父页面发送数据 */
      window.parent.postMessage({
        msg: "hideselfService"
      }, '*');
    }
    window.addEventListener('message', function (e) {
      console.log(e.data.data, '子页面输出');
    })
  </script>
</body>

</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容