parent-index.html: (本地起服务,放在5000端口上)

<div class="content">
    <iframe src="http://localhost:5001/public/second.html" ></iframe>	
</div>
<script type="text/javascript">
//当前脚本
function resize() {
    var ifr = document.getElementById('sendMessage');
    //使用iframe的window向iframe发送message。
    ifr.contentWindow.postMessage("123", "http://localhost:5001");
    window.addEventListener('message', function (e) {
        alert('回传 ' + e.data)
    })
}
</script>

child-second.html: (本地起服务,放在5001端口上)

<div class="content"> 
    <div >xxxxx</div>
</div>
<script type="text/javascript">
    window.addEventListener('message', receiver, false);
    function receiver(e) {
       if (e.data) {
           console.log(e)
           // 注释掉的为单次父子交互
           // var obj = {'name': 'qwer','age': 'xxx'}
           // e.source.postMessage(JSON.stringify(obj), e.origin);
           // console.log(e.data)
          document.getElementById('howMuch').onclick = function second() { 
              // 父子建立联系后,儿子html可以通过点击事件多次主动向父亲传值
              var obj = {'name': 'qwer','age': 'xxx'}
              window.parent.postMessage(JSON.stringify(obj), 'http://localhost:5000')
          }
      } else {
         alert(e.data);
     }
}
</script>

.

相关文章:

  • 2022-01-26
  • 2022-12-23
  • 2021-12-24
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-09-17
  • 2022-01-15
  • 2022-01-22
相关资源
相似解决方案