<iframe>(Inline Frame)允許在頁面中嵌入另一個獨立 HTML 文檔。從早期的「畫中畫」廣告位,到現代的微前端子應用容器、第三方組件嵌入(支付、地圖、編輯器),iframe 依然不可替代。本文系統整理屬性、父子通信、樣式隔離、跨域方案、SEO 影響、安全策略與現代替代技術。
核心屬性速查
| 屬性 | 值/說明 | 備註 |
| src | URL | 嵌入頁面地址,支持相對/絕對路徑、data URI、javascript:、about:blank |
| width / height | 像素/百分比 | CSS 控制優先,屬性作為兜底 |
| name | 字符串 | **關鍵**:供 ``, ` |
| frameborder | 0 / 1 (HTML5 棄用) | 改用 CSS `border: none` |
| scrolling | yes / no / auto (HTML5 棄用) | 改用 CSS `overflow` |
| marginwidth / marginheight | 像素 (棄用) | 改用 CSS `padding`/`margin` |
| allow | 權限策略字符串 | 如 `camera`, `microphone`, `fullscreen`, `payment` 等 |
| allowfullscreen | 布爾屬性 | 允許 `requestFullscreen()`,現代寫法用 `allow="fullscreen"` |
| loading | lazy / eager | 原生懶加載 (Chrome 77+) |
| referrerpolicy | no-referrer / origin / ... | 控制 Referer 頭 |
| sandbox | 空格分隔的權限列表 | **安全核心**,見下文詳解 |
| srcdoc | HTML 字符串 | 直接指定內容,無需外部請求,配合 sandbox 極其安全 |
沙箱屬性 `sandbox` 詳細權限
<iframe sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-top-navigation-by-user-activation" src="..."></iframe>
| Token | 允許行為 | 風險 |
| (無/默認) | 完全限制:異源、腳本、表單、彈窗、頂層導航、插件、指針鎖定 | 最安全 |
| allow-scripts | 運行 JavaScript | 可竄改父頁 DOM (若同源) |
| allow-same-origin | 保持同源身份 (而非 opaque origin) | 配合 scripts 可突破同源策略 |
| allow-forms | 提交表單 | 釣魚表單風險 |
| allow-popups | window.open / target=_blank | 彈窗騷擾 |
| allow-top-navigation | iframe 導航頂層窗口 | 劫持整頁跳轉 |
| allow-top-navigation-by-user-activation | 用戶手勢觸發時允許頂層導航 | 較安全,推薦替代上一項 |
| allow-downloads | 下載文件 | 惡意下載 |
| allow-modals | alert/confirm/prompt | 阻塞 UI |
| allow-pointer-lock | Pointer Lock API | 遊戲/沉浸式體驗 |
| allow-presentation | Presentation API | 投屏 |
父子頁面通信(同源)
父 → 子
const iframe = document.getElementById('myFrame');
iframe.onload = () => {
iframe.contentWindow.childFn('param');
// 或訪問子頁變量
console.log(iframe.contentWindow.someVar);
};
子 → 父
// 子頁面
window.parent.parentFn('data');
window.parent.document.getElementById('parentEl').style.color = 'red';
同級幀互調
// left.html 調用 right.html
window.parent.document.getElementById('rightFrame').contentWindow.rightFn();
跨域通信:`window.postMessage`(標準、安全、唯一正解)
<!-- 父頁面 -->
<iframe id="child" src="https://other-domain.com/child.html"></iframe>
<script>
const child = document.getElementById('child');
child.onload = () => {
// 發送消息,指定目標 origin (安全!)
child.contentWindow.postMessage({type: 'INIT', data: {token: 'abc'}}, 'https://other-domain.com');
};
window.addEventListener('message', e => {
// **必須驗證 origin**
if (e.origin !== 'https://other-domain.com') return;
if (e.data.type === 'READY') { /* ... */ }
});
</script>
<!-- 子頁面 (https://other-domain.com/child.html) -->
<script>
window.addEventListener('message', e => {
if (e.origin !== 'https://parent-domain.com') return;
if (e.data.type === 'INIT') {
initApp(e.data.data.token);
// 回覆父頁
e.source.postMessage({type: 'READY'}, e.origin);
}
});
</script>
樣式隔離與穿透
- **同源**:父頁 CSS **無法**直接穿透進 iframe 內部(影子 DOM 邊界)
- **注入樣式**:`iframe.contentDocument.head.appendChild(styleEl)`
- **CSS Modules / Shadow DOM / Styled Components** 現代方案天然隔離
- **跨域**:完全無法操作內部樣式,需雙方約定 CSS 變量或 postMessage 同步主題
SEO 影響
- Google **能抓取並索引** iframe 內容,但權重歸屬於 **src URL**,而非父頁
- 重要內容**不要**只放在 iframe,主頁面應有語義化降級內容或預渲染
- `` 可阻止 iframe 頁被單獨索引
安全最佳實踐
- **始終加 `sandbox`**,按需開啟最小權限
2. **第三方嵌入**務必指定 `allow="..."` 而非 `allowfullscreen` 全開
3. **CSP 配合**:`frame-ancestors 'self' https://trusted.com;` 防止被惡意嵌入
4. **X-Frame-Options**:`DENY` / `SAMEORIGIN` 保護自身不被嵌入
5. **postMessage 必驗證 `e.origin`**,防止偽造消息注入
現代替代方案對比
| 方案 | 適用場景 | 隔離性 | SEO | 複雜度 |
| iframe | 第三方嵌入、跨域隔離、舊系統包裹 | 最高(進程級/沙箱) | 分離索引 | 低 |
| Web Components (Shadow DOM) | 組件庫、設計系統、樣式隔離 | 樣式/JS 隔離(同進程) | 同頁索引 | 中 |
| Micro-frontends (Module Federation / single-spa / qiankun) | 大型應用拆分、團隊獨立部署 | JS 隔離(沙箱)、樣式隔離 | 同頁索引 | 高 |
| Server Components / Edge Includes (Next.js / Astro / Cloudflare) | 服務端組合、性能關鍵 | 無客戶端隔離 | 完美 SSR | 中 |
| Web Workers / Service Workers | 計算密集、離線、推播 | 執行緒隔離 | 無 DOM | 中高 |
結語
iframe 是 Web 平台最強大的**隔離容器**。善用 `sandbox`、`allow`、`postMessage`、`CSP`,能在安全與功能間找到平衡。新架構下,優先評估 Web Components、微前端、Server Components 等現代替代,將 iframe 保留給「不可控的第三方內容」與「極致隔離需求」場景。