JS 重新整理頁面看似簡單,實則有多種情境與寫法差異。本文系統整理:基本重整、框架/iframe 跨頁刷新、子視窗刷新父視窗、自動定時重整、Meta 標籤重導、伺服器端輸出重導腳本等實用模式。
// 1. 標準重新載入 (最常用)
location.reload();
// 或帶參數強制從伺服器重取 (true=繞過快取)
location.reload(true);
// 2. 簡寫
location = location;
location.href = location.href;
// 3. 替換歷史記錄 (不留歷史,無法「上一頁」回來)
location.replace(location.href);
// 4. history 物件
history.go(0); // 相當於 reload()
history.go(-1); // 返回上一頁
history.back(); // 同上
history.forward(); // 前進
// 5. document.execCommand (IE 專屬,已棄用)
document.execCommand('Refresh');
// 6. window.navigate (IE 專屬,已棄用)
window.navigate(location.href);
假設頂層 `frameset` 或 `iframe` 結構:
<frameset rows="50%,50%">
<frame name="top" src="top.html">
<frame name="bottom" src="bottom.html">
</frameset>
<input type="button" value="刷新1" onclick="window.parent.frames[1].location.reload()">
<input type="button" value="刷新2" onclick="window.parent.frames.bottom.location.reload()">
<input type="button" value="刷新3" onclick="window.parent.frames['bottom'].location.reload()">
<input type="button" value="刷新4" onclick="window.parent.frames.item(1).location.reload()">
<input type="button" value="刷新5" onclick="window.parent.frames.item('bottom').location.reload()">
<input type="button" value="刷新6" onclick="window.parent.bottom.location.reload()">
<input type="button" value="刷新7" onclick="window.parent['bottom'].location.reload()">
解析:`window`=當前框架、`parent`=父框架、`frames`=子框架集合 (可用索引/名稱/`item()` 存取)。現代建議統一用 parent.frames['name'] 或 parent.frames[index]。
parent.location.reload();
// 或
top.location.reload(); // 最頂層
<script>
// 子視窗執行
self.opener.location.reload(); // 刷新父視窗
window.opener = null; // 斷開關聯
window.close(); // 關閉自己
</script>
<body onload="opener.location.reload()"> <!-- 開啟時刷新父視窗 -->
<body onUnload="opener.location.reload()"> <!-- 關閉時刷新父視窗 -->
<head>
<!-- 20 秒重新整理當前頁 -->
<meta http-equiv="refresh" content="20">
<!-- 20 秒後跳轉到指定網址 -->
<meta http-equiv="refresh" content="20;url=https://example.com">
</head>
<script>
function myRefresh() {
window.location.reload();
}
// 每 1 秒重新整理一次
setInterval(myRefresh, 1000);
// 或僅一次延遲重新整理
setTimeout(myRefresh, 5000); // 5 秒後重新整理
</script>
處理完表單/動作後,直接輸出 JS 重導/刷新父頁:
<%
' ASP 範例
Response.Write ""
Response.End
%>
";
echo "window.opener.location.reload();";
echo "window.close();";
echo "";
exit;
?>
| 情境 | 推薦做法 | 避免 |
|---|---|---|
| 一般頁面重新整理 | location.reload() | location=location (語意不明) |
| 表單送出後防止重複提交 | PRG 模式:header("Location: ...") / Response.Redirect | JS 重新整理 (F5 仍會重送) |
| 局部更新 | Fetch/AJAX + DOM 更新 | 整頁重新整理 |
| 跨域 iframe 通訊 | postMessage API | 直接存取 parent.frames (同源策略阻擋) |
| 單頁應用 (SPA) 路由切換 | Router push/replace | location.reload |
掌握 location.reload()、parent/opener/top 參考鏈、``、伺服器端輸出腳本,即可應付 99% 的頁面重新整理/重導需求。現代開發應優先採用 **PRG 模式 (伺服器端 302 Redirect)** 與 **AJAX 局部更新**,減少整頁重載、提升使用者體驗。