多个iframe和父级互相通信
- father.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>
<style>
iframe {
width: 100%;
}
</style>
</head>
<body>
<iframe src="./son1.html" frameborder="0"></iframe>
<iframe src="./son2.html" frameborder="0"></iframe>
<script>
// 1. 定义子组件传参类型
window.iframeNameData = {
SON1: 'SON1',
SON2: 'SON2',
}
// 2. 定义子组件发送函数
window.iframeSendMessage = function(type, data) {
window.parent.postMessage({
type,
data
})
}
// 3. 获取iframeDom对象
const [son1, son2] = document.querySelectorAll('iframe')
// 4. 监听iframe通知事件
function receiveMessageIframePage(messageEvent) {
const type = messageEvent.data.type
switch (type) {
case window.iframeNameData.SON1:
console.log(`父组件接收son1信息:`,messageEvent.data)
// iframeDom对象通过contentWindow属性获取iframe的window对象
// 调用子组件方法传递信息
son1.contentWindow.receiveFatherInfo('父组件发送给son1的信息')
break;
case window.iframeNameData.SON2:
console.log(`父组件接收son2信息:`,messageEvent.data)
son1.contentWindow.receiveFatherInfo('父组件发送给son2的信息')
break;
default:
throw new Error('传入了错误类型')
break;
}
}
window.addEventListener('message', receiveMessageIframePage, false)
</script>
</body>
</html>
- son1.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>
hello, 我是son1
<script>
function receiveFatherInfo(info) {
console.log(`我是子组件son1:${info}`)
}
setTimeout(() => {
window.parent.iframeSendMessage(window.parent.iframeNameData.SON1, {
msg: 'hello, 我是son1'
})
}, 1500)
</script>
</body>
</html>
- son2.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>
hello, 我是son2
<script>
function receiveFatherInfo(info) {
console.log(`我是子组件son2:${info}`)
}
setTimeout(() => {
window.parent.iframeSendMessage(window.parent.iframeNameData.SON1, {
msg: 'hello, 我是son2'
})
}, 3000)
</script>
</body>
</html>
最后,启动方式不能双击打开,请按照https://blog.csdn.net/weixin_45326220/article/details/134081446方式启动项目
获取iframe框架里面的document对象
iframe框架里面的网页,使用iframe节点的contentDocument属性。
document.defaultView属性返回document对象所属的window对象。如果当前文档不属于window对象,该属性返回null。