我用的sublimeServer插件服务器。
直接上代码!!
主页面:
<!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://localhost:8080/self/testpostmessage/testsave.html"></iframe>
</div>
<script type="text/javascript">
window.onload=function(){
var targetOrigin = 'http://localhost:8080/self/testpostmessage/testsave.html';
window.frames[0].postMessage('getcolor','http://localhost:8080/self/testpostmessage/testsave.html');
};
window.addEventListener('message',function(e){
var color=e.data;
document.getElementById('color').style.backgroundColor=color;
},false);
</script>
</body>
</html>
iframe内部页面:
<!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,'*');
// console.log(e.origin);
if(e.origin=='http://localhost:8080/self/testpostmessage/test1.html'){
console.log(e.origin)
}
},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;
console.log(window.parent.postMessage);
window.parent.postMessage(color,'*');
}
</script>
</body>
</html>
需要注意的几个点:
1、子页面一定要在主页面监听message之前监听message
2、window.parent.postMessage(color,'*') 第一个参数为要发送的数据,第二个限定接收的主页面url(只识别到协议主机端口号)*为所有都可接收
3、window.frames[0].postMessage('getcolor','http://localhost:8080/self/testpostmessage/testsave.html');主页面这句话的两个参数没多大卵用
3.1:父传子也可以。
4、接收数据e的主要属性:
- data:顾名思义,是传递来的message
- source:发送消息的窗口对象
- origin:发送消息窗口的源(协议+主机+端口号)
so可以看一下html5另一个API——web workers了
来个红心,关注呗~