zoukankan      html  css  js  c++  java
  • location.hash 实现跨域 iframe 自适应

    转发:http://www.oschina.net/code/snippet_54100_592

    实现效果:

    A域名下的页面a.html中通过iframe嵌入B域名下的页面b.html,由于b.html的宽度和高度是不可预知而且会变化的,所以需要a.html中的iframe自适应大小.

    问题本质:

    js对跨域iframe访问问题,因为要控制a.html中iframe的高度和宽度就必须首先读取得到b.html的大小,A、B不属于同一个域,浏览器为了安全性考虑,使js跨域访问受限,读取不到b.html的高度和宽度.

    解决方案:

    引入代理代理页面c.html与a.html所属相同域A,c.html是A域下提供好的中间代理页面,假设c.html的地址:www.taobao.com/c.html ,它负责读取location.hash里面的width和height的值,然后设置与它同域下的a.html中的iframe的宽度和高度.

    a.html

    1 <!-- 首先a.html中通过iframe引入了b.html -->
    2 <iframe id="b_iframe" height="0" width="0" src="http://zw.zftec.gov.cn/b.html" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" allowtransparency="yes">

    b.html

     1 <script type="text/javascript">
     2     var b_width = Math.max(document.documentElement.clientWidth, document.body.clientWidth);
     3     var b_height = Math.max(document.documentElement.clientHeight, document.body.clientHeight);
     4     var c_iframe = document.getElementById("c_iframe");
     5     c_iframe.src = c_iframe.src + "#" + b_width + "|" + b_height; //http://zw.zftec.gov.cn/c.html#width|height”
     6   </script>
     7   <!--
     8   js读取b.html的宽和高,把读取到的宽和高设置到和a.html
     9   在同一个域的中间代理页面车c.html的src的hash里面
    10   -->
    11   <iframe id="c_iframe" height="0" width="0" src="http://zw.zftec.gov.cn/c.html" style="display:none"></iframe>

    c.html

    1 <script type="text/javascript">
    2     var b_iframe = parent.parent.document.getElementById("b_iframe");
    3     var hash_url = window.location.hash;
    4     var hash_width = hash_url.split("#")[1].split("|")[0] + "px";
    5     var hash_height = hash_url.split("#")[1].split("|")[1] + "px";
    6     b_iframe.style.width = hash_width;
    7     b_iframe.style.height = hash_height;
    8   </script>
    9   <!-- a.html中的iframe就可以自适应为b.html的宽和高了. -->
  • 相关阅读:
    云如何解决安全问题 狼人:
    存储安全 系统的最后一道防线 狼人:
    云安全仍是企业决策者最大担心 狼人:
    骇客宣称已入侵多家认证机构 波及微软、谷歌 狼人:
    盘点云计算服务中的隐患 狼人:
    云服务安全吗?美国政府用实际行动告诉你 狼人:
    微软高层称移动设备越多 对信息安全需更多考量 狼人:
    云计算需要让安全优先 狼人:
    金山网络两月被黑4次 入侵黑客留名挑衅 狼人:
    惠普推出全新企业级安全软件 狼人:
  • 原文地址:https://www.cnblogs.com/qzsonline/p/2966247.html
Copyright © 2011-2022 走看看