父级
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="">
<iframe id="iframe" src="http://xxx/child.html" frameborder="0"></iframe>
<button type="button" id="btn">给子组件传值</button>
</div>
</body>
<script type="text/javascript">
let btn = document.getElementById('btn');
let iframe = document.getElementById('iframe');
btn.onclick = () => {
iframe.contentWindow.postMessage("父组件给子组件的数据", 'http://xxx/child.html')
}
window.addEventListener('message', function (event) {
console.log('event_father', event);
}, false);
</script>
</html>
子级
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="">
<button type="button" id="btn">给父组件传值</button>
</div>
</body>
<script type="text/javascript">
let btn = document.getElementById('btn');
btn.onclick = () => {
top.postMessage("子组件给父组件的数据", 'http://xxx/father.html')
}
window.addEventListener('message', function (event) {
console.log('event_child', event);
}, false);
</script>
</html>