我们在开发过程中,会遇到有需求,在A页面中嵌套一个iframe的B页面,B页面需要发消息给A页面,A页面接收消息,做出相应的处理。这时我们就需要postMessage和addEventListener进行配合使用
用法
window.postMessage(message, targetPage, [transfer])
message: 将要发送到其他 window的数据
targetPage:通过窗口的origin属性来指定哪些窗口能接收到消息事件,其值可以是字符串"*"(表示无限制)或者一个URI。在发送消息的时候,如果目标窗口的协议、主机地址或端口这三者的任意一项不匹配targetOrigin提供的值,那么消息就不会被发送
transfer:可选参数。是一串和message 同时传递的 Transferable 对象. 这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权。
例子
B页面向A页面发送消息
B页面代码:
<html>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<button id="bt">button</button>
</html>
<script>
var data={"event":'pay','name':'60pic'}
$("#bt").click(function(){
console.log(data)
window.parent.postMessage(data,'http://localhost');
})
</script>
window.postMessage中的window始终是你要通信的目标页面的window,而这里A页面才是通信的目标页面,所以需要用window.parent。
A页面代码:
<html>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<iframe src="b.html" name="iframe1" id="iframe1"></iframe>
</html>
<script>
window.addEventListener('message',function(e){
console.log(e)
},false)
</script>
A页面向B页面发送消息
A页面代码:
<html>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<iframe src="b.html" name="iframe1" id="iframe1"></iframe>
<button id="bt2">A-button</button>
</html>
<script>
var data={"event":'pay','name':'60pic'}
$("#bt2").click(function(){
document.getElementById("iframe1").contentWindow.postMessage(data,'*')
})
</script>
B页面代码:
<html>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<button id="bt">button</button>
</html>
<script>
window.addEventListener("message",function(e){
console.log(e);
})
</script>