1、postMessage函数的用法
windows.postMessage(msg,targetOrigin)是客户端与客户端直接的数据传递,既可以跨域也是可同域传递。
注意:msg是你想要发送的信息,而targetOrigin是“目标源”,比如你要2.com的网页往1.com的网页发送信息,目标源填写"http://1.com/" 一个完整的域包括 域名 主机名 端口号 如:http://g.cn:80/
目标源也可以写"*"通配符,不过这样安全性较低。
如果是同源传递信息,目标源填写"/"来限制信息只能同源传递
2、在目标页面获取信息
获取postMessage()传来的信息进行处理,就要在页面上加入onmessage事件(最好是通过标准事件addEventListener或者IE事件attachEvent来添加onmessage事件,而不是直接windows.onmessage=function(){},因为这样有的浏览器识别不了,例如低版本的火狐)
windows.addEventListener("message",function(e)
{
console.log(e.origin,e.data);
alert("有数据来了");
}
);
onmessage事件就是这个e,里面包含了data(传递的数据),origin(发送消息窗口的源(协议 主机 端口号))比如从2.com往1.com发了消息,那么1.com收到消息时,e.origin就是2.com,sourse就是发送消息的窗口对象
3、实例(这里引用了别人的一个服务器文件,借鉴的别人的博客)
postmessage.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
iframe
{
width: 600px;
height: 500px;
}
</style>
</head>
<body>
<button id="send">发送到另一个文档</button>
<button id="open">打开另一个页面</button><br />
<iframe id="other" src="http://jhssdemo.duapp.com/demo/h5_postmessage/win.html"></iframe><!--这里的src引用的是别人的服务器文件-->
<input type="text" />
<button id="sendbtn">发送到ifram</button>
<script type="text/javascript">
var win;
document.getElementById("open").οnclick=function(){//为open按钮设置点击事件,打开另一个文档
win=window.open("http://jhssdemo.duapp.com/demo/h5_postmessage/win.html");
}
document.getElementById("send").οnclick=function()
{
win.postMessage('GoogLucky',"http://jhssdemo.duapp.com/");
}
function f()
{
document.getElementById('other').contentWindow
.postMessage(document.getElementsByTagName("input")[0].value,"http://jhssdemo.duapp.com/");
}
document.getElementById("sendbtn").οnclick=function()
{
f();
}
</script>
</body>
</html>
另个一个是相对于这个跨域的一个文件,运行在服务器里,你可以直接引用,如果你有服务器的话,可以借鉴这个代码。如果没有,直接引用就行了,只写上面那个文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Html5 postMessage</title>
<style>
#txt {
width: 500px;
height: 300px;
background-color: #cccccc;
}
</style>
</head>
<body>
<h1>The New Window</h1>
<div id="txt"></div>
<script>
window.onload = function() {
var text = document.getElementById('txt');
//监听函数,接收一个参数--Event事件对象
function receiveMsg(e) {
console.log("Got a message!");
console.log("nMessage: " + e.data);
console.log("nOrigin: " + e.origin);
text.innerHTML = "Got a message!<br>" +
"Message: " + e.data +
"<br>Origin: " + e.origin;
}
if (window.addEventListener) {
//为window注册message事件并绑定监听函数
window.addEventListener('message', receiveMsg, false);
}else {
window.attachEvent('message', receiveMsg);
}
};
</script>
</body>
</html>