[JavaScript]父子窗口间参数传递

概述

当页面嵌入一个iframe,或者打开一个子窗口。这个时候如果父窗口需要与子窗口之间通讯,如果直接用DOM访问对方窗口window,会受到跨于安全机制影响。

javascript提供一个方法,可以解决这个问题,window.postMessage()

示例

1.与iframe通讯

主页面:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<iframe id="iframe_1" src="http://192.168.5.136:10013/tmp_75.html"></iframe>
<!-- <iframe id="iframe_1" src="./temp_1263.html"></iframe> -->
<script type="text/javascript">
  var iframe_1 = document.getElementById("iframe_1");
  iframe_1.addEventListener("load", function(e){
    e.target.contentWindow.postMessage({"foo": 1}, "*");
  }, false);

  window.addEventListener("message", receiveMessage, false);
  function receiveMessage(event) {
    console.log(event);
  }

</script>
</body>
</html>

子页面:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<script type="text/javascript">
    window.addEventListener("message", receiveMessage, false);
    function receiveMessage(event) {
        console.log(event);
        window.parent.postMessage({"bar": 1}, "*");
    }
</script>
</body>
</html>

双方页面监听"message"事件,父页面等待子页面加载完毕后调用子窗口的window.postMessage发送信息,子窗口收到信息后触发"message"回调函数,回调函数中往父窗口的window.postMessage发送信息,父窗口收到消息后触发"message"回调函数

2.与子窗口通讯

跟iframe不同之处在于,可能是出于某种安全机制的设计,通过window.open返回的window对象无法让父窗口监听该window对象的事件。

这就意味着父窗口无法通过事件去得知子窗口何时加载完毕,并且在何时适合调用window.postMessage发送信息

有一种解决办法是让子窗口通过window.opener对象,调用父窗口的方法来到通知它子窗口已经就绪。

主页面:

 

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<a id="a_1">open</a>
<script type="text/javascript">
  var a_1 = document.getElementById("a_1");
  var win_1;
  a_1.addEventListener("click", function(e){
    win_1 = window.open('./tmp_77.html','_blank','width=200,height=100');
  }, false);

  window.addEventListener("message", receiveMessage, false);
  function receiveMessage(event) {
    console.log(event);
  }

  function subWinReady(){
    win_1.postMessage({"foo": 1}, "*");
  }
</script>
</body>
</html>

 

子页面:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<script type="text/javascript">
    window.opener.postMessage({"bar": 1}, "*");
    window.addEventListener("message", receiveMessage, false);
    function receiveMessage(event) {
        console.log(event);
    }
    //调用父页面方法
    window.opener.subWinReady();
</script>
</body>
</html>

注意:这种方式在跨域下是无效的,因为跨域下双方页面不能通过获取对方window对象直接调用其方法。

 

转载于:https://www.cnblogs.com/yiyide266/p/11064842.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值