主页面:http://ext.js.com
跨域:http://hb.test.com
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>跨域通信示例</title>
<script type="text/javascript">
window.addEventListener("message",function(ev){
if(ev.origin != "http://hb.test.com"){
return;
}
document.getElementById("h").innerHTML = "从"+ev.origin + "那里传过来的消息:\n" + ev.data ;
},false);
function hello(){
var iframe= window.frames[0];
iframe.postMessage("你好","http://hb.test.com");
}
</script>
</head>
<body>
<h1>跨域通信</h1>
<iframe width="400" src="http://hb.test.com/a1.html" οnlοad="hello()"></iframe>
<div id="h">
</div>
</body>
</html>
iframe页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>跨域通信示例</title>
<script type="text/javascript">
window.addEventListener("message",function(ev){
if(ev.origin != "http://ext.js.com"){
return;
}
document.body.innerHTML="从"+ev.origin + "那里传来的消息。<br />" + ev.data ;
ev.source.postMessage("您好,这里是"+this.location, ev.origin);
},false);
</script>
</head>
<body>
</body>
</html>