…….續前緣
前文說到的jsonp, 正在向前端靠攏. 而本文所說的postMessage, 跟後臺已經沒有任何關係了. 因爲用的是HTML5 新API: canvas, video, audio, history, postMessage.
百度百科對它的解釋如下: PostMessage是Windows API(應用程序接口) 中的一個常用函數,用於將一條消息放入到消息隊列中。
戰前準備: 兩個**非同源**website, 請見jsonp的戰前準備
請求方(request)和響應方(response). request.html如下(wamp):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>請求方</title>
<meta content="initial-scale=1.0,maximum-scale=1.0,width=device-width" name="viewport">
</head>
<body>
<div class="form-wrap">
<button ontouchstart="fnSearch();">查詢</button>
</div>
</body>
<script>
function fnSearch(){
var newWindow = window.open('http://localhost:8020/test2/response.html');
window.addEventListener('message', function(e){
if (e.data) {
newWindow.postMessage('hello world!', e.origin);
console.log(e);
}
});
}
</script>
</html>
response.html如下(HBuilder):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>手機時間選擇</title>
<meta content="initial-scale=1.0,maximum-scale=1.0,width=device-width" name="viewport">
</head>
<body>
<div class="form-wrap">
<button id="search" type="button">查詢</button>
</div>
</body>
<script type="text/javascript">
document.getElementById('search').onclick = function(){
window.opener.postMessage('測試123', 'http://localhost:80/chart/index.html');
window.addEventListener('message',function(e){
console.log(e);
}, false);
};
</script>
</html>
在兩個頁面的控制檯就可以看到交互的信息了, 如果有任何問題, 可以給我留言啊. 我會及時回覆滴……………………