js_window.postMessage往不同窗口里面发送数据


一个页面通过iframe引入另外一个页面,页面之间如何通讯?两个页面就存在两个window,存在跨域。父子页面可以通过window.postMessage进行通讯。

1、子页面使用window.postMessage通讯;

2、父页面使用window.addEventListener("message", receiveMessage, false);实时接收子页面的数据。


 

父窗口

<iframe src="test2.html"></iframe>
<script>
    function receiveMessage(e) {
      alert(e.data);
    }
    window.addEventListener("message", receiveMessage, false);
</script>

 

子窗口test2.html

<input type="text" value="send" id="input" />
<input type="button" value="send" id="button" />
<script>
  document.getElementById('button').onclick = function () {
      top.postMessage(document.getElementById('input').value, '*');
  };
</script>

 

参考地址

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM