使用window.postmessage方法來跨域
Html5里有一個(gè)屬性window.postmessage也可以用來跨域:
postmessage(data,origin)有兩個(gè)參數(shù):
data: 要傳遞的數(shù)據(jù)岸军,html5規(guī)范中該參數(shù)可以是JavaScript的任意基本類型或可復(fù)制的對(duì)象吃环,考慮到部分瀏覽器只能處理字符串參數(shù)设江,所以在傳遞參數(shù)的時(shí)候需要使用JSON.stringify()方法對(duì)對(duì)象參數(shù)序列化煞抬,對(duì)postmessage()方法的支持度為IE8+混萝;
origin: 字符串參數(shù)狱杰,指明目標(biāo)窗口的源屹耐;設(shè)置為* 則為通配,這樣可以傳遞給任意窗口臼膏,如果要指定和當(dāng)前窗口同源的話設(shè)置為"/"
例如有兩個(gè)頁面:
在http://test.com/index.html中發(fā)送信息:
<script>
var obj= {
key: 'values'
}
window.onload=function(){
win.postMessage(obj,'http://receive.com/index.html');
}
</script>
然后再在http://receive.com/index.html中接受消息硼被,渲染顯示:
window.onmessage=function(e){
if(e.origin !== 'http://test.com/index.html') return; //做一下安全性判斷,看看消息是否是由可信源頭發(fā)送
console.log(e.origin+' '+e.data.key); //接受跨域數(shù)據(jù)渗磅,渲染
}
//http://test.com/index.html values
window.postmessage()也可用在iframe的通信中嚷硫,例如(該實(shí)例來源于:http://www.cnblogs.com/dolphinX/p/3464056.html):
<!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>