早期教程常使用 `document.frames[0].location.href = url`,但此寫法**僅在 IE 生效**,現代瀏覽器(Chrome、Firefox、Edge、Safari)均不支援 `document.frames` 集合,導致跨瀏覽器相容性極差。
推薦使用標準 DOM API,支援所有主流瀏覽器:
// 取得 iframe 元素
const iframe = document.getElementById('myIframe');
// 方法 1:直接修改 src 屬性(最簡單、觸發完整導航)
iframe.src = 'https://example.com/new-page.html';
// 方法 2:操作 contentWindow.location(可保留歷史記錄行為)
iframe.contentWindow.location.href = 'https://example.com/new-page.html';
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>動態切換 Iframe 來源示範</title>
<style>
#targetFrame { width: 100%; height: 400px; border: 1px solid #ccc; }
button { margin-right: 8px; padding: 6px 12px; cursor: pointer; }
</style>
</head>
<body>
<button onclick="changeSrc('https://developer.mozilla.org/')>MDN Web Docs</button>
<button onclick="changeSrc('https://web.dev/')>web.dev</button>
<button onclick="changeSrc('https://caniuse.com/')>Can I use</button>
<iframe id="targetFrame" src="https://example.com/" title="動態內容區"></iframe>
<script>
function changeSrc(url) {
const frame = document.getElementById('targetFrame');
// 現代瀏覽器統一支援 src 屬性賦值
frame.src = url;
}
</script>
</body>
</html>
若 iframe 指向**不同源**(協議、域名、埠口任一不同),受同源策略限制,父頁面**無法**讀取或操作 iframe 內部 DOM,但**依然可以修改 `src` 導向新 URL**。
| 需求 | 解決方案 |
|---|---|
| 父頁面與 iframe 雙向通訊 | 使用 `window.postMessage()` 進行安全跨域傳訊 |
| 監聽 iframe 載入完成 | `iframe.onload = () => { console.log('loaded'); }` |
| 動態建立 iframe 並載入 | `const f = document.createElement('iframe'); f.src = url; container.appendChild(f);` |
| 阻止 iframe 內部跳轉頂層頁面 | 給 iframe 加上 `sandbox="allow-scripts allow-forms"`(移除 `allow-top-navigation`) |
修改 Iframe `src` 的標準寫法極其簡單:`iframe.src = '新網址'`。拋棄舊式 `document.frames` 寫法,擁抱標準 DOM API,即可獲得完美的跨瀏覽器相容性與可維護性。