一、文章参考
二、知识点
-
页面需要监听 message 事件,window.addEventListener(“message”, dealMessage, false);
-
父页面向子iframe页面发送消息:
document.getElementById("mapIframe").contentWindow.postMessage("父页面向子页面发送消息", "*");
或者
document.getElementById("mapIframe").contentWindow.postMessage("父页面给子页面发送信息", "http://10.192.195.166:56225/son.html");
- 子iframe页面向父页面发送消息:
window.parent.postMessage('子页面向父页面发送消息','*');
三、例子说明
- 父页面
<!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>我是父亲页面</div>
<button onclick="parentMsgToSon()">父页面给子页面发送信息</button>
<!-- <iframe
id="mapIframe"
src="http://127.0.0.1:9999/son.html"
style="width: 500px; height: 500px"
></iframe> -->
<iframe
id="mapIframe"
src="http://10.192.195.166:54473/son.html"
style="width: 500px; height: 500px"
></iframe>
</body>
<script>
// 父页面向子页面发送消息
function parentMsgToSon() {
document.getElementById("mapIframe").contentWindow.postMessage("父页面向子页面发送消息", "*");
}
// 监听子页面的消息
if (typeof window.addEventListener != "undefined") {
// for ie9+、chrome
window.addEventListener("message", dealMessage, false);
} else if (typeof window.attachEvent != "undefined") {
// for ie8-
window.attachEvent("onmessage", dealMessage);
}
// 处理消息的回调函数
function dealMessage(e) {
console.log(e.data);
}
</script>
</html>
- 子页面
<!DOCTYPE html>
<html lang="en">
<body>
<div>我是子页面</div>
<button onclick="sendMsgToParent()">子页面给父页面发送信息</button>
</body>
<script>
// 向iframe父页面发送消息
function sendMsgToParent() {
window.parent.postMessage('子页面向父页面发送消息', '*');
}
// 监听消息
if (typeof window.addEventListener != 'undefined') { // for ie9+、chrome
window.addEventListener('message', dealMessage, false);
} else if (typeof window.attachEvent != 'undefined') { // for ie8-
window.attachEvent('onmessage', dealMessage);
}
// 监听消息的回调函数
function dealMessage(e) {
console.log(e.data);
}
</script>
</html>
3.1 能不能使用非message事件?
不能,否则起不到效果
四、通信的前提是iframe 加载完成
4.1 问题描述
在工作中,由于iframe的地址src 是变动的,于是,自己在写代码的时候,iframe一旦变化之后就立马向iframe发送消息,一直到不到预期的效果,但是技术路线好像又没有问题,经过反复调试和代码审查发现,是由于iframe 里面的代码还没有加载完成就发送消息,导致iframe 子页面没有处理消息信息的逻辑
4.2 解决办法,iframe 添加 onload 事件
<!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>
<button onclick="test()">改变</button>
<iframe id="aaa" src="https://www.baidu.com" onload="iframeLoad()"></iframe>
</body>
</html>
<script>
console.log('start')
function iframeLoad () {
console.log('load')
alert('页面加载完成')
}
console.log('end')
function test () {
document.getElementById('aaa').src = 'http://hui.dev.hikhub.net/zh/form/input.html#%E5%A4%8D%E5%90%88%E5%9E%8B%E8%BE%93%E5%85%A5%E6%A1%86'
}
</script>