[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对象直接调用其方法。

 

posted @ 2019-06-24 11:06  yiyide266  阅读(2274)  评论(0编辑  收藏  举报