前提:父页面和子页面不同域
首先是父页面传数据给子页面
parent.html
<iframe src="http://IP:8018/child.html" frameborder="1" id="ifr1" name="ifr1" scrolling="yes">
<p>Your Browser dose not support iframes</p>
</iframe>
<script>
var myIframe = document.getElementById('ifr1')
myIframe.contentWindow.postMessage(document.getElementById('message').value, 'http://IP:8018')
</script>
child.html
<script>
window.addEventListener('message', function (e) {
alert(e.data)
})
</script>
需要注意的是一定要加上http://,同时统一用IP都用IP,用域名都用域名,用localhost都用localhost。

本文介绍了在不同域的iframe中进行数据通信的方法。父页面通过`postMessage`将数据传递给子页面,而子页面则使用事件监听来接收数据。为了解决子页面可能未加载完成导致的数据丢失问题,提出了一种解决方案:先通过一个与父页面同源的辅助页面fchild.html进行通信,然后再由fchild将数据传递给子页面。同时,子页面也可以通过`postMessage`向父页面发送数据。
最低0.47元/天 解锁文章
1391

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



