Chrome 154 中的回應式 iframe

發布日期:2026 年 9 月 16 日

Chrome 154 版新增回應式大小的 iframe 支援功能,可讓 <iframe> 根據內嵌文件的固有大小調整自身大小。這項功能非常適合無縫嵌入第三方留言小工具、高度不一的社群媒體嵌入內容,或使用 <iframe> 的任何其他類型嵌入內容。

Browser Support

  • Chrome: behind a flag.
  • Edge: behind a flag.
  • Firefox: not supported.
  • Safari: not supported.

Source

開發人員通常會手動測量 iframe 內容、使用 postMessage() 傳送尺寸,並在嵌入頁面中手動更新 iframe 大小,而回應式 iframe 則可取代這種常見模式。

這段錄影畫面顯示使用 iframe 嵌入網頁的留言表單。使用者新增留言時,內嵌網頁中的 iframe 高度會動態更新,打造流暢的視覺體驗,不會出現捲軸。

根據內容調整 iframe 大小

根據預設,iframe 有自己的可視區域。如果內嵌文件的高度超過可視區域,使用者可能會看到額外的捲軸。如果使用自動調整大小的 iFrame,嵌入網頁可以改用以內容為準的大小:

.embed {
  width: 100%;
  frame-sizing: content-height;
}

內嵌文件必須選擇加入:

<meta name="responsive-embedded-sizing" content="allow-origins=*">

完整範例如下:

<style>
  .embed {
    width: 100%;
    frame-sizing: content-height;
  }
</style>
<iframe class="embed" src="/comments.html" title="Comments">
</iframe>

/comments.html 中:

<!doctype html>
<html>
  <head>
    <meta name="responsive-embedded-sizing" content="allow-origins=*">
  </head>
  <body>
    ...
  </body>
</html>

iframe 現在可以使用內嵌文件的內容高度,而非像固定高度的可視區域。

使用frame-sizing

新的 frame-sizing 屬性可控制要從 iframe 內容衍生哪個維度。

支援的值包括:

frame-sizing: auto;
frame-sizing: content-width;
frame-sizing: content-height;
frame-sizing: content-inline-size;
frame-sizing: content-block-size;

auto 會保留現有的 iframe 大小調整行為。

在大多數橫向書寫模式中,content-heightcontent-block-size 是垂直擴展嵌入內容最實用的值。

您也可以將 frame-sizing 與其他 CSS 限制條件合併:

.embed {
  width: 100%;
  max-height: 80vh;
  frame-sizing: content-height;
}

在動態內容變更後調整大小

瀏覽器不會持續觀察內嵌文件中的每個版面配置變更。

如果 iframe 的內容在初始版面配置後有所變更 (例如載入更多留言或展開面板),內嵌文件可以使用 window.requestResize() 要求重新計算大小。

async function loadMore() {
  const items = await fetchMoreItems();
  renderItems(items);
  window.requestResize();
}

建議您在完成文件的所有變更後,再於版面配置前呼叫 window.requestResize()。這種明確的更新模型有助於避免大小調整迴圈,也就是變更 iframe 大小會變更其可視區域,進而變更內容,然後再次變更大小。

跨來源嵌入

如果使用跨來源 iframe,也可以採用回應式大小。內嵌文件可以限制允許的來源:

<meta
  name="responsive-embedded-sizing"
  content="allow-origins=https://publisher.example">

這樣一來,系統就只會根據 https://publisher.example 調整大小。多個來源以半形空格分隔:content="allow-origins=https://publisher1.example https://publisher2.example"

如果是第三方小工具,請限制只允許需要存取的來源存取。這項機制可補強現有的 iframe 安全控管措施,例如內容安全政策的 frame-ancestors 指令,該指令可控管哪些網站能嵌入網頁。

漸進增強

您可以使用功能查詢,為不支援 frame-sizing 的瀏覽器保留現有的備用方案:

.widget {
  width: 100%;
  height: 500px;
}

@supports (frame-sizing: content-height) {
  .widget {
    height: auto;
    frame-sizing: content-height;
  }
}

如果嵌入的文件會動態更新,您也可以進行特徵偵測 requestResize()

if ("requestResize" in window) {
  window.requestResize();
}

因此,在支援範圍擴大期間,現有的 iframe 大小調整程式碼仍可做為備援。

試試看

請參閱下列示範,瞭解如何調整 iframe 大小以配合螢幕大小: