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>

  • 相关阅读:
    js中(function(){…})()立即执行函数写法理解
    css3 样式 圆角
    Hbuilder实用技巧
    开始使用 HBuilder 和 Mui
    init和plus(编码中遇到问题就看这里)
    将id传过去,根据id显示下面的详情页面
    iOS-上传头像的使用
    iOS-iOS 支付 [支付宝、银联、微信](转)
    iOS-ShareSDK的使用(转)
    iOS-在AFN基础上进行网络请求的封装
  • 原文地址:https://www.cnblogs.com/antonyhubei/p/5316631.html
Copyright © 2011-2022 走看看