父元素

<!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>
  <h1>I am Father</h1>
  <iframe frameborder="1" id="childIframe" src="http://127.0.0.1:5500/index.html" frameborder="0"></iframe>
</body>
<script>
  const iframeWrap = document.querySelector('#childIframe');
  iframeWrap.onload = function () {
    console.log('【父】子页面加载完成');
    const parentData = '父容器传递给子容器的数据'
    iframeWrap.contentWindow.postMessage(parentData, '*')
    // console.log(iframeWrap.contentWindow.fn());
  }

  // 父页面接受子页面的数据
  window.addEventListener('message', (e) => {
    console.log('【父】', e)
  }, false);
</script>

</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>
  <h1>I am children</h1>
</body>
<script>
  const fn = () => {
    alert("【子】啦啦啦")
  }
  window.addEventListener('message', function (e) {
    console.log('【子】接收到数据', e);
    e.source.postMessage("确认收到消息", "*");
  })
</script>

</html>