2.source:发送消息的窗口对象
3.origin:发送消息窗口的源(协议+主机+端口号)
这样就可以接收跨域的消息了,我们还可以发送消息回去,方法类似
简单的demo
在这个例子中,左边的div会根据右边iframe内div颜色变化而变化


<!DOCTYPE html>
<html>
<head>
<title>Post Message</title>
</head>
<body>
<div style="width:200px; float:left; margin-right:200px;border:solid 1px #333;">
<div id="color">Frame Color</div>
</div>
<div>
<iframe id="child" src="http://lsLib.com/lsLib.html"></iframe>
</div> <script type="text/javascript">
window.onload=function(){
window.frames[0].postMessage('getcolor','http://lslib.com');
}
window.addEventListener('message',function(e){
var color=e.data;
document.getElementById('color').style.backgroundColor=color;
},false);
</script>
</body>
</html>
http://test.com/index.html
<!doctype html>
<html>
<head>
<style type="text/css">
html,body{
height:100%;
margin:0px;
}
</style>
</head>
<body style="height:100%;">
<div id="container" onclick="changeColor();" style="widht:100%; height:100%; background-color:rgb(204, 102, 0);">
click to change color
</div>
<script type="text/javascript">
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>
http://lslib.com/lslib.html
在例子中页面加载的时候主页面向iframe发送’getColor‘ 请求(参数没实际用处)
window.onload=function(){
window.frames[0].postMessage('getcolor','http://lslib.com');
}iframe接收消息,并把当前颜色发送给主页面呢









