父页面
<body>
父级:A页面<br/><br/>
<button id="children_button">传值给子元素 </button>
<iframe src="http://www.genetek.cc/iframe/b.html" width="500px" height="200px" id="iframe"></iframe>
<script>
let iframe = document.getElementById('iframe');
document.getElementById("children_button").onclick = function(){
var param = {'age':'10'};
iframe.contentWindow.postMessage(param,'*');
}
</script>
</body>
子页面
<body>
子级:B页面<br/>
<button id="b_button">B页面发送A页面数据</button><br/>
<script>
window.addEventListener('message', function(e) {
document.getElementById("b_button").innerHTML=JSON.stringify(e.data);
alert(JSON.stringify(e.data));
})
</script>
</body>
跨窗口传值实践
本文介绍了一种在父页面与子页面间通过iframe实现数据传递的方法。具体展示了如何使用JavaScript的postMessage API从父页面向子页面发送数据,并在子页面中接收并显示这些数据。此方法适用于不同域名下的窗口通信。
198

被折叠的 条评论
为什么被折叠?



