平時(shí)做web開發(fā)的時(shí)候關(guān)于消息傳遞,除了客戶端與服務(wù)器傳值還有幾個(gè)經(jīng)常會(huì)遇到的問題
1.頁(yè)面和其打開的新窗口的數(shù)據(jù)傳遞
2.多窗口之間消息傳遞
3.頁(yè)面與嵌套的iframe消息傳遞
4.上面三個(gè)問題的跨域數(shù)據(jù)傳遞
這些問題都有一些解決辦法,但html5引入的message的API可以更方便、有效、安全的解決這些難題。postMessage()方法允許來(lái)自不同源的腳本采用異步方式進(jìn)行有限的通信,可以實(shí)現(xiàn)跨文本檔、多窗口、跨域消息傳遞。
postMessage(data,origin)方法接受兩個(gè)參數(shù)
1.data:要傳遞的數(shù)據(jù),html5規(guī)范中提到該參數(shù)可以是JavaScript的任意基本類型或可復(fù)制的對(duì)象,然而并不是所有瀏覽器都做到了這點(diǎn)兒,部分瀏覽器只能處理字符串參數(shù),所以我們?cè)趥鬟f參數(shù)的時(shí)候需要使用JSON.stringify()方法對(duì)對(duì)象參數(shù)序列化,在低版本IE中引用json2.js可以實(shí)現(xiàn)類似效果。
2.origin:字符串參數(shù),指明目標(biāo)窗口的源,協(xié)議+主機(jī)+端口號(hào)[+URL],URL會(huì)被忽略,所以可以不寫,這個(gè)參數(shù)是為了安全考慮,postMessage()方法只會(huì)將message傳遞給指定窗口,當(dāng)然如果愿意也可以建參數(shù)設(shè)置為"*",這樣可以傳遞給任意窗口,如果要指定和當(dāng)前窗口同源的話設(shè)置為"/"。
父頁(yè)面
<!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>
iframe頁(yè)面
<!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>