使用postMessage实现页面之间的通信
核心代码只有postMessage那一段
这是主页面的代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"/>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<title>Document</title>
</head>
<style>
#ifrom{
width: 500px;
height: 300px;
border: 1px solid #000000;
margin-left: 500px;
}
</style>
<body >
//ifram组件,在加载完成之后调用load这个函数
<iframe id="ifrom" src="./ifrom.html" frameborder="0" onload="load()"></iframe>
<div>父组件</div>
</body>
<script>
function load(){
//固定写法,获取ifram的节点的窗口
const ifrom=document.getElementById('ifrom').contentWindow
//使用postMessage往所获取的ifrom窗口中传递信息
ifrom.postMessage('父元素发来的信息','*')
}
//并且监听ifram窗口传来的数据
window.addEventListener('message',function(e){
console.log(e,1111)
})
</script>
</html>
下面是ifram窗口里面的页面
- 这是一个地图的插件,我用的事百度地图,具体ifram页面中写什么,根据需求来定
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Document</title>
</head>
<style>
html{height:100%}
body{height:100%;margin:0px;padding:0px}
#map{
width: 500px;
height: 250px;
background-color: red;
border: 1px solid #000000;
}
#suggestId {
width: 300px;
}
</style>
<body>
<div class="header">
<input type="text" id="suggestId" placeholder="请输入查询关键词"><button onclick="search()" >搜索</button>
</div>
<div id="map">ifrom</div>
</body>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=sricStBmCa6YNnfuccDwyHlo7oTotVw6"></script>
<script>
//百度地图api固定写法
var map = new BMap.Map("map");
var point = new BMap.Point(116.404, 39.915);
map.centerAndZoom(point, 15);
map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
map.addEventListener("click", function(e){
console.log(e.Ag);
});
var ac = new BMap.Autocomplete( //建立一个自动完成的对象
{
"input": "suggestId"
, "location": map
});
function search(){
let data=document.getElementById('suggestId').value;
find(data)
}
// 创建地址解析器实例
var myGeo = new BMap.Geocoder();
function find(data){
// 将地址解析结果显示在地图上,并调整地图视野
myGeo.getPoint(data, function(point){
console.log(point,4444)
if (point) {
map.centerAndZoom(point, 16);
map.addOverlay(new BMap.Marker(point));
}
}, "*");
}
//在ifram中设置监听,监听父元素传来的数据
window.addEventListener('message',function(e){
//打印父页面传来的数据
console.log(e);
//这是往父元素传递信息的方法,这样就实现了在接收到父页面传来的信息之后打印出来,并且向父元素传递信息,接收了父元素的传值
window.parent.postMessage('接收了父组件的传值','*')
})
</script>
</html>
其实以上介绍了简单的通信,一般实际开发中,比如ifram中嵌套百度地图小页面,用户在点击完成之后需要将ifram中的数据传到父页面这样就会用到子传父,另外如果需求需要再地图加载完成之后默认选中某个地址,那么我们就需要提前将所徐亚选择的数据,通过postMessage传到子页面中,这样就用到了父传子;以上是我用到的场景