思路:
父传子:
发送方:
iframe.contentWindow.postMessage('要传的参数', '*')
接收方:
window.addEventListener("message", function(e){...}, false) // e是个对象,里面包含了传过来的参数
子传父:
发送方:
parent关键字表示父窗口,如果一个窗口没有父窗口,则它的 parent 属性为自身的引用.
parent.postMessage('要传的参数', '*')
接收方:
window.addEventListener("message", function(e){...}, false) // e是个对象,里面包含了传过来的参数
父页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.father {
width: 500px;
height: 500px;
margin: 0 auto;
background-color: brown;
border: 2px solid black;
}
iframe {
width: 200px;
height: 200px;
margin: 0 auto;
display: block;
background-color: bisque;
border: 2px solid black;
}
#btn {
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="father">
<p></p>
<iframe src="./iframe-子页面.html" frameborder="0" id="iframe"></iframe>
<button id="btn">父传子</button>
<script>
const iframe = document.getElementById('iframe')
const btn = document.getElementById('btn')
const p = document.querySelector('p')
const receiveMsg = function(e) {
const { data } = e
if (data.id === 'son') {
p.innerText = data.msg
p.style.color = 'white'
}
}
btn.onclick = function (e) {
iframe.contentWindow.postMessage({
id: 'father',
msg: '要传给子页面的值'
}, '*')
}
window.addEventListener("message", receiveMsg, false)
window.a = '父页面'
</script>
</div>
</body>
</html>
子页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
</style>
</head>
<body>
<div class="son">
<b></b>
<button onclick="sendMsg()">子传父</button>
</div>
<script>
//监听message事件
const b = document.querySelector('b')
const receiveMsg = function (e) {
const { data } = e
if (data.id === 'father') {
b.innerText = data.msg
}
}
window.addEventListener("message", receiveMsg, false)
const sendMsg = function() {
parent.postMessage({
id: 'son',
msg: '传给父页面的值'
}, '*')
}
console.log(window.parent.a) // 父页面
</script>
</body>
</html>