使用iframe实现
实现效果
- http://localhost:3000/bbb.html点击【点击】向http://localhost:3001/b.html发送数据
- http://localhost:3001/b.html接受并在控制台打印数据
实现原理:
- http://localhost:3000/bbb.html(简称bbb页面)嵌入iframe页面http://localhost:3001/a.html(简称iframe页面)
- iframe能够接受父级页面bbb.html发送过来的数据
- 与此同时iframe与实际需要接受数据的http://localhost:3001/b.html(简称b页面)同源,所以可以通过同源通信的Broadcast Channel方式将iframe接受到的数据发送给b页面实现bbb页面与b页面之间的数据发送
bbb.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<iframe src="http://localhost:3001/a.html"></iframe>
<div id='click'>点击</div>
<script>
click.onclick = function () {
// 向iframe发送数据,iframe端口3001,与当前bbb.html不同源。但是发送数据给iframe
window.frames[0].window.postMessage('使用iframe作为中介发送数据', '*')
}
</script>
</body>
</html>
iframe页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
a.html
<script>
window.addEventListener('message', function (e) {
// 接受非同源父页面(http://localhost:3000/bbb.html)发送的数据,
// 使用BroadcastChannel进行广播数据( b.html 与当前iframe同源 同属于3001端口 ,所以 b.html可以接收到广播出去的数据)
const data = e.data
// 通过BroadCast Channel 向当前同源页面通信
const bc = new BroadcastChannel('iframe_connect');
bc.postMessage(e.data)
})
</script>
</body>
</html>
b页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
b.html
<!-- <iframe width="0" height="0" src="http://localhost:3001/c.html"></iframe> -->
<script>
const bc = new BroadcastChannel('iframe_connect')
bc.onmessage = function (e) {
// 接受iframe广播出来的数据并打印
console.log('receive:',e.data);
}
</script>
</body>
</html>
508