iframe通信方法 传递数据 window.postMessage的使用

我们在开发过程中,会遇到有需求,在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>
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值