在 Web 開發中,iframe 常被用於嵌入外部頁面或隔離功能模組。當需要在不重新加載整個父頁面的情況下更新 iframe 內容時,掌握幾種可靠的刷新技巧顯得尤為重要。本文系統梳理了 JavaScript 操作 iframe 刷新的主流方式,並針對跨域、多 iframe 協作等實際場景給出針對性方案。
假設頁面中存在如下 iframe:
<iframe src="1.htm" name="ifrmname" id="ifrmid"></iframe>
利用 document.frames 集合或 document.all 獲取 iframe 窗口對象,調用其 location.reload():
<input type="button" value="刷新" onclick="document.frames('ifrmname').location.reload()">
<!-- 或 -->
<input type="button" value="刷新" onclick="document.all.ifrmname.document.location.reload()">
此法適用於同域環境,代碼簡潔,但 document.frames 為 IE 專屬屬性,現代瀏覽器建議改用 window.frames。
現代瀏覽器會自動將帶有 id 的 iframe 映射為全局變量,可直接調用:
<input type="button" value="刷新" onclick="ifrmid.window.location.reload()">
這是最直觀的寫法,但需注意變量名不得與全局變量衝突。
受同源策略限制,無法直接訪問跨域 iframe 的 location。此時可通過重新加載 src 實現「刷新」效果:
<input type="button" value="刷新" onclick="window.open(document.all.ifrmname.src, 'ifrmname', '')">
本質上是在同名窗口中重新打開原 URL,雖會觸發導航歷史記錄,但能繞過跨域限制。
典型案例:左側列表 iframe、右側詳情 iframe。詳情頁提交新增數據後,需刷新列表而不影響詳情頁。
// 在詳情 iframe 的提交回調中
window.parent.frames["listFrame"].location = "list_url"; // 精準刷新列表頁
// 詳情頁自身可正常跳轉或刷新,互不干擾
document.frames("refreshAlarm").location.reload(true);
document.frames("refreshAlarm").document.location.reload(true);
document.frames("refreshAlarm").document.location = "https://example.com/";
document.frames("refreshAlarm").src = "https://example.com/";
關鍵區別:document.frames("name") 返回的是 iframe 元素節點,操作其 src 屬性有效;而 .document 才指向 iframe 內部文檔,調用 location.reload() 需作用於後者。
<meta http-equiv="refresh" content="10;url=目標頁面URL">
<script>
setTimeout("location.href='目標URL'", 2000); // 2秒後跳轉
</script>
<script>
window.location.reload(true); // 強制從服務器獲取
// 刷新 iframe 只需將 window 替換為對應 iframe 的 name 或 id
</script>
function autoRefresh() {
window.location.href = window.location.href;
setTimeout(autoRefresh, 10000); // 每10秒刷新一次
}
<script>
top.leftFrm.location.reload(); // 刷新頂層左側框架
parent.frmTop.location.reload(); // 刷新父頁面頂部框架
</script>
掌握上述方法,可靈活應對單頁應用、後台管理系統、嵌入式儀表盤等各類 iframe 刷新需求。實際項目中建議優先使用標準 DOM API(iframeEl.contentWindow.location.reload()),兼容性最佳且語義清晰。