zoukankan      html  css  js  c++  java
  • PostMessager来对子父窗体进行跨域

    一.为什么需要使用postMessage这个跨域技术

    对于一个普通的页面而言,如果页面中的数据量太多时,会导致某个页面的数据量太多 二显得特别的臃肿,所以通常是使用iframe的方式来加载子页面,但是我们使用了iframe来加载子页面后,通常又涉及到子页面与父页面直接的信息的交替,比如我的父页面中有许多的功能时,会导致页面中的表单、表格、对话框(dialog)就很多,我们通常会将某些它们单独的分配到其他的子页面中去,如添加表单,但是当我们的表单添加功能,父页面是显示数据库中的数据同时包含了添加的数据,这时如果想要我的子页面中的表单提交后,我的父页面中的表格也相对的进行刷新同步时,我们就涉及到了子页面和父页面之间的信息的交互问题,这时我们通常是使用postMessage来进行交互。

    二、使用postMessage常用的步骤

      1、在父页面添加监听

      //事件监听

      window.addEventListener('message',function(e){
          var mes = e.data;
          alert(mes);
         if(mes == "app_refresh"){
           mediaTableObj.refresh();
       }
     },false);

      2、在子页面中当完成某个操作后进行交互中发送消息

      //发送消息 

      window.parent.postMessage("app_refresh",'*');

    三、具体的实例

    A、父页面:

    !DOCTYPE html>

    <html>
      <head>
        <title>Post Message</title>
      </head>
      <body>
        <div style="200px; float:left; margin-right:200px;border:solid 1px #333;">
          <div id="color">Frame Color</div>
        </div>
        <div>
          <iframe id="child" src="test2.html"></iframe>
        </div>

    <script type="text/javascript">
      window.addEventListener('message',function(e){
        var color=e.data;
        console.log(e);
        document.getElementById('color').style.backgroundColor=color;
      },false);
    </script>
    </body>
    </html>

    B、子页面

    <!doctype html>

    <html>
      <head>
      <style type="text/css">
        html,body{
          height:100%;
          margin:0px;
        }
      </style>
      </head>
      <body style="height:100%;">
        <div id="container" onclick="changeColor();" style="widht:100%; height:100%; background-color:rgb(204, 102, 0);">
          click to change color
        </div>

      </body>
      <script type="text/javascript">
        var container=document.getElementById('container');
        function changeColor () {
          var color=container.style.backgroundColor;
          if(color=='rgb(204, 102, 0)'){
            color='rgb(204, 204, 0)';
          }else{
            color='rgb(204,102,0)';
          }
          container.style.backgroundColor=color;
          window.parent.postMessage(color,'*');
        }
      </script>
    </html>

  • 相关阅读:
    javsscript闭包的一种使用场景--沙箱
    toString()方法,与call()方法结合;用来进行数据类型检测
    [学习笔记]数论(二)
    [模板]平面最近点对
    [bzoj1670][Usaco2006 Oct]Building the Moat
    [模板]计算几何(一)
    [日常训练]string
    [bzoj3626][LNOI2014]LCA
    [bzoj2732][HNOI2012]射箭
    [学习笔记]半平面交
  • 原文地址:https://www.cnblogs.com/antonyhubei/p/5316631.html
Copyright © 2011-2022 走看看