跨文档消息传输
H5提供了网页文档之间互相接收与发送消息的功能。当在A页面中通过window.open方法打开B页面,或者在A页面中通过iframe嵌套B页面,我们想让A中的数据传递到B中就可以使用跨文档消息传输
A页面代码
<!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>A</title>
<script>
// 通过window.open打开B页面
// A页面打开新窗口
window.onload=function(){
// 获取button按钮
var btn = document.querySelector('button');
// 获取发送数据按钮
var sendBtn = document.querySelector("#send");
var iframe = document.querySelector('#iframe');
// 点击btn打开一个新窗口
var win;
btn.onclick = function(){
// 打开一个新窗口
win = window.open('./B1.html');
}
sendBtn.onclick = function(){
// 发送消息
var obj = {
name:'hhh',
age:11
}
win.postMessage(obj,'http://127.0.0.1:5500');
win.postMessage('hello');
}
// 给第三个按钮绑定事件
iframe.onclick = function(){
// 获取内联窗口发送数据
win = document.querySelector('iframe').contentWindow;
}
}
</script>
</head>
<body>
<button>打开新窗口获取B1</button>
<button id="send">发送数据</button>
<button id="iframe">获取内联框架(获取B页面)</button>
<iframe src="./B.html" frameborder="0"></iframe>
</body>
</html>
B页面代码
<!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>B</title>
<style>
body{
height: 400px;
background-color: aquamarine;
}
</style>
<script>
// 获取A传的消息
window.onmessage = function(event){
// 获取消息
console.log(event.data);
// 获取源
console.log(event.origin);
}
</script>
</head>
<body>
</body>
</html>
打开新窗口:
通过内联框架得到的结果: