萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 透過 iframe 載入外部網頁並自適應高度完整實作

前言

在同域或跨域 (需協作) 情況下,透過 <iframe> 嵌入外部頁面並自動調整高度以消除雙滾動條,是常見需求。本文提供完整實作方案:動態計算高度、跨域通訊、樣式隔離。

同域環境:直接存取 DOM 調整高度

父頁面

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>父頁面</title>
  <style>
    body, html { margin:0; padding:0; height:100%; overflow:hidden; }
    #externalFrame { width:100%; border:none; display:block; }
  </style>
</head>
<body>
  <iframe id="externalFrame" src="https://example.com/page.html"></iframe>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(function() {
      const $frame = $('#externalFrame');
      // 方法 1: onload 後直接讀取內容高度 (同域)
      $frame.on('load', function() {
        try {
          const doc = this.contentDocument || this.contentWindow.document;
          const height = Math.max(
            doc.body.scrollHeight, doc.documentElement.scrollHeight,
            doc.body.offsetHeight, doc.documentElement.offsetHeight
          );
          $frame.height(height + 20); // 留白
        } catch (e) {
          console.warn('跨域無法讀取:', e);
        }
      });

      // 方法 2: 監聽視窗大小變化重新計算
      $(window).on('resize', () => $frame.trigger('load'));
    });
  </script>
</body>
</html>

跨域環境:postMessage 協作方案

**前提**:子頁面控制權在你手中,可植入腳本。

父頁面

<iframe id="childFrame" src="https://child-domain.com/page.html" style="width:100%;border:none;"></iframe>
<script>
  const $frame = $('#childFrame');
  window.addEventListener('message', function(e) {
    // 安全性:驗證來源
    if (e.origin !== 'https://child-domain.com') return;
    if (e.data && e.data.type === 'iframeResize') {
      $frame.height(e.data.height + 20);
    }
  });
</script>

子頁面

<script>
  function reportHeight() {
    const height = Math.max(
      document.body.scrollHeight, document.documentElement.scrollHeight,
      document.body.offsetHeight, document.documentElement.offsetHeight
    );
    parent.postMessage({ type: 'iframeResize', height }, 'https://parent-domain.com');
  }
  // 頁面載入、資源載入、視窗變化時上報
  window.addEventListener('load', reportHeight);
  window.addEventListener('resize', reportHeight);
  // 圖片載入後也需重新計算
  document.querySelectorAll('img').forEach(img => {
    img.addEventListener('load', reportHeight);
  });
  // 定時輪詢兜底 (針對動態內容)
  setInterval(reportHeight, 500);
</script>

進階:iframe-auto-height 輕量庫封裝

// 父頁面引入
function setupIframeAutoHeight(iframeSelector, options = {}) {
  const { allowedOrigin = '*', debounce = 100 } = options;
  let timer;
  window.addEventListener('message', e => {
    if (allowedOrigin !== '*' && e.origin !== allowedOrigin) return;
    if (e.data?.type === 'iframeResize') {
      clearTimeout(timer);
      timer = setTimeout(() => {
        document.querySelector(iframeSelector).style.height = e.data.height + 'px';
      }, debounce);
    }
  });
}

// 子頁面引入
function initIframeReporter(options = {}) {
  const { targetOrigin = '*', interval = 500 } = options;
  const calc = () => Math.max(
    document.body.scrollHeight, document.documentElement.scrollHeight,
    document.body.offsetHeight, document.documentElement.offsetHeight
  );
  const report = () => parent.postMessage({ type: 'iframeResize', height: calc() }, targetOrigin);
  ['load', 'resize'].forEach(evt => window.addEventListener(evt, report));
  document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('img, iframe').forEach(el => el.addEventListener('load', report));
  });
  setInterval(report, interval);
}

樣式隔離與安全建議

  • sandbox 屬性:<iframe sandbox="allow-scripts allow-same-origin allow-forms"> 限制子頁面權限。
  • CSP:父頁面設定 Content-Security-Policy: frame-src 'self' https://trusted.com;。
  • X-Frame-Options:被嵌入頁面可設定 SAMEORIGIN 或 DENY 防止被任意嵌入。
  • 滾動條控制:父頁面 overflow:hidden,iframe scrolling="no",由父頁面統一滾動。

常見問題排查

現象原因解決
高度為 0 或不變跨域無法讀取 contentDocument改用 postMessage 方案
高度忽大忽小圖片/字體載入後重排子頁面監聽 img.onload、font loading API
雙滾動條父頁面未隱藏 overflow、iframe 有 scrolling父頁面 overflow:hidden, iframe scrolling="no"
白屏/拒絕連線目標站設定 X-Frame-Options: DENY無法解決,需對方開放或改用代理/截圖

總結

同域用 onload 直接量測最簡單;跨域必須雙方協作用 postMessage。封裝成可複用函式庫並處理「圖片載入重排」、「動態內容輪詢」、「防抖」三大細節,即可獲得穩定體驗。安全性務必驗證 e.origin 並善用 sandbox。

copyright © 萬盛學電腦網 all rights reserved