H5提供了网页文档之间互相接收与发送消息的功能。当在a页面中通过window.open方法打开b页面,或者在a页面中通过iframe嵌套b页面,我们想让a中的数据传递到b中就可以使用跨文档消息传输
通过第一个页面打开窗口,iframe 创造内联窗口
第一个页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
window.onload=function(){
var btn1=document.querySelector('button');
var btn2=document.getElementsByTagName('button')[1];
var btn3=document.getElementsByTagName('button')[2];
var win;
btn1.onclick=function(){
// 打开b1页面
win=window.open('./9-B页面.html')
}
btn2.onclick=function(){
win.postMessage('hello','*')
}
}
</script>
</head>
<body>
<!-- 实现跨文档通信 -->
<button>打开B页面</button>
<button>发送数据</button>
<br>
<iframe src="./9-B页面.html" frameborder="0"></iframe>
</body>
</html>
第二个页面,这个页面是第一个的内联样式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
height: 400px;
background-color: cyan;
}
</style>
<script>
//onmessage接受信息
window.onmessage=function(e){
console.log(e.data);
console.log(e.origin);
}
</script>
</head>
<body>
B页面
</body>
</html>