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 }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章