版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m_review/article/details/81461791
本文讲的是: iframe 嵌套不同源页面通过 postMessage 通信
直接上代码:自己拿去尝试一下。
父页面可以是本地的一个html文件;
子页面是用node写的一张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>
<div style="width: 200px;float: left;margin-right: 200px;border: 1px solid #333;">
<div id="color"> frame color</div>
</div>
<div>
<iframe id="child" src="http://localhost:3000/"></iframe>
</div>
<script>
window.onload = function() {
// 初始化div颜色
window.frames[0].postMessage('getcolor', 'http://localhost:3000/');
}
window.addEventListener('message',function(e) {
// 监听子页面颜色的改变即发送的消息,设置div颜色
var color = e.data;
document.getElementById('color').style.backgroundColor = color;
},false)
</script>
</body>
</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>
<div id="container" onclick="changeColor();" style="width: 100%; height: 100%;background-color: rgb(204,102,0)">
click to change color
</div>
<script>
var container = document.getElementById('container');
window.addEventListener('message', function (e) {
if(e.source != window.parent) return ;
var color = container.style.backgroundColor;
window.parent.postMessage(color,'*');
},false)
function changeColor() {
var color = container.style.backgroundColor;
if(color=='rgb(204, 102, 0)'){
color='rgb(204, 204, 0)';
}else{
color='rgb(204,102,0)';
}
container.style.backgroundColor = color;
// 给父元素发送消息
window.parent.postMessage(color,'*');
}
</script>
</body>
</html>