iframe 巢狀不同源頁面怎麼通訊
阿新 • • 發佈:2018-10-31
本文講的是: 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>