zoukankan      html  css  js  c++  java
  • iframe跨域动态设置主窗口宽高

    Q:
    在A项目的a页面嵌入一个iframe,
    src是B项目的b页面,
    怎样让a页面的高度跟b页面的高度一样?

    A:
    解决跨域方案:增加一个A项目的c页面。


    操作步骤:

    一,a页面的iframe设置: 获取到当前域名,作为参数设置到src上

    1 <iframe id={idname} title=" " scrolling="no" src={`${iframeUrl}?zeus=${locationOrigin}`} >

      

    二,b页面页脚增加以下代码:
    通过location拿到a页面的域名,请求A项目的c页面,并将b页面的宽度高度/宽度通过src传到c页面。

     1 <script type="text/javascript">
     2 !(function (){
     3     var search = window.location.search;
     4     if(!search || search.indexOf('zeus') === -1)return;
     5      var query = {};
     6      search.slice(1).split('&').forEach(function(item){
     7          var a = item.split('=');
     8         query[a[0]] = a[1];
     9      })
    10     if(query.zeus){
    11         var body = document.body;
    12         var w = Math.max(body.scrollWidth, body.clientWidth);
    13         var h = Math.max(body.scrollHeight, body.clientHeight);
    14         var iframeNode = document.createElement('iframe');
    15         iframeNode.style.display = 'none';
    16         iframeNode.src = query.zeus + '/m/iframe/ware#' + w + '|' + h;
    17         body.appendChild(iframeNode);
    18     }
    19 })();
    20 </script>  

    三,c页面添加以下代码:
    通过location拿到b页面的宽高,然后设置a页面的宽高,done!

     1 const setIframeWH = () => {
     2   const outerWindow = window.parent.parent;
     3   const locationPathname = outerWindow.location.pathname;
     4   const idname = locationPathname.replace(///gi, '__');
     5   let iframeMain = outerWindow.document.getElementById(idname);
     6   let hash = window.location.hash;
     7   if (iframeMain && hash.indexOf('#') >= 0) {
     8     let [width, height] = hash.slice(1).split('|');
     9     iframeMain.style.width = `${width}px`;
    10     iframeMain.style.height = `${Number(height) + 50}px`;
    11   }
    12 }
  • 相关阅读:
    TP5学习笔记- 使用命令行创建控制器
    centos 7 下安装mysql5.7
    webserver的安装
    linux常用命令 服务器硬件资源信息
    SSH 安装/ config 配置以及免密码登录
    thinkphp ,laravel,yii2运行环境搭建.
    分享几个博客园代码样式的CSS配置(复制黏贴即可)
    vue中通过.sync修饰符实现子组件修改父组件数据
    vue中$attrs和$listeners以及inheritAttrs的用法
    Vue项目中实现用户登录及token验证
  • 原文地址:https://www.cnblogs.com/ronffy/p/8302569.html
Copyright © 2011-2022 走看看