H5 Notes:PostMessage Cross-Origin Communication
Javascript中要实现跨域通信,主要有window.name,jsonp,document.domain,cors等方法。不过在H5中有一种新的方法postMessage可以安全实现跨域通信,并且使用简单。
要使用postMessage,首先得检查浏览器是否支持该方法,postMessage属于window对象,检测方法如下:
if('postMessage' in window){ }else{ console.log('浏览器不支持postMessage'); }
postMessage使用语法如下所示。
otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow必须是一个window对象的引用,如iframe的contentWindow,window.open的返回对象,window.frames[index]等。
targetOrigin指定otherWindow的源,如果目标窗口的协议,主机地址,端口只要一个不同,该方法便不会执行信息发送
为了能接收到postMessage发送的消息,必须在window对象上监听message事件,该事件对象包涵了data(消息)、origin(来源地址)、source(来源窗口代理)等属性,使用如下所示
window.onmessage = function(e){ if (e.origin === 'http://www.test.zmx.com') { alert(e.data); } }
下面是使用postMessage的小例子,帮助理解。
http://www.test.zmx.com/postmessage.html,简称A页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<iframe frameborder="0" src="http://www.select.zmx.com/select.html"></iframe>
<input type="text" id="kw"><button id="btn">发送到子窗口</button>
<script type="text/javascript">
window.onload = function(){
window.onmessage = function(e) {
if (e.origin === 'http://www.select.zmx.com') {
alert("收到来自子窗口的消息:"+e.data);
}
}
btn.onclick = function(e) {
var val = kw.value;
window.frames[0].postMessage(val, 'http://www.select.zmx.com');
}
}
</script>
</body>
</html>
http://www.select.zmx.com/select.html,简称B页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>简单下拉框插件</title>
<link rel="stylesheet" href="simpleSelect.css">
<style type="text/css">
body{ padding: 40px; }
</style>
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script type="text/javascript" src="simpleSelect.js"></script>
</head>
<body>
<input type="text" id="in1"><button id="btn1">发送到父窗口</button>
<script>
window.onmessage = function(e){
if (e.origin === 'http://www.test.zmx.com') {
alert("收到来自父窗口的消息:"+e.data);
}
}
btn1.onclick = function(e) {
var val = in1.value;
window.top.postMessage(val, 'http://www.test.zmx.com');
}
</script>
</body>
</html>
在A页面中发送消息hello world给B页面,如下所示。

点击发送,则B页面则收到消息,如下所示。

B页面向A页面发送消息也是一样的,就不叙述了。

浙公网安备 33010602011771号