parent-index.html: (本地起服务,放在5000端口上)
<div class="content"> <iframe src="http://localhost:5001/public/second.html" id="sendMessage" name="sendMessage" onload="resize()"></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 id="howMuch">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>
.