前言
歷史導航 (`history` 物件) 與頁面重新整理 (`location.reload` 等) 是前端開發高頻操作。本文系統整理所有標準與非標準方法、參數、相容性、最佳實務與陷阱,供開發者快速查閱。
一、History 物件:歷史導航
標準方法 (HTML5 規範)
| 方法 | 說明 | 參數 | 回傳值 | 備註 |
history.back() | 返回上一頁 | 無 | undefined | 等同 `history.go(-1)` |
history.forward() | 前進下一頁 | 無 | undefined | 等同 `history.go(1)` |
history.go(delta) | 相對跳轉 | 整數 (正前進、負後退) | undefined | `go(0)` 重新整理當前頁 |
history.pushState(state, title, url) | 新增歷史記錄 | state 物件、標題 (忽略)、URL | undefined | 不觸發頁面載入,SPA 必備 |
history.replaceState(state, title, url) | 替換當前記錄 | 同上 | undefined | 不增加歷史長度 |
history.length | 歷史堆疊長度 | 唯讀屬性 | 整數 | 含當前頁,最小 1 |
history.state | 當前狀態物件 | 唯讀屬性 | 任意可序列化物件 | 配合 `popstate` 事件 |
實用範例
// 返回上一頁 (最常用)
<a href="javascript:history.back()">返回</a>
<button onclick="history.back()">返回</button>
// 返回兩頁
history.go(-2);
// 表單送出確認後返回
if (!confirm('確定送出?')) history.back();
// SPA 路由核心
history.pushState({page: 'detail', id: 123}, '', '/detail/123');
window.addEventListener('popstate', e => {
if (e.state) loadPage(e.state.page, e.state.id);
});
二、頁面重新整理:8 種方法大比較
| 方法 | 語法 | 特性 | 相容性 | 推薦度 |
1. location.reload() | `location.reload([forceGet])` | 標準、支援強制從伺服器重載 (`true`) | 全瀏覽器 | ⭐⭐⭐⭐⭐ 首選 |
2. history.go(0) | `history.go(0)` | 利用歷史機制重載,可能走快取 | 全瀏覽器 | ⭐⭐⭐ 簡潔但語意不明 |
3. location = location | `location = location.href` | 觸發導航,同 `location.href = location.href` | 全瀏覽器 | ⭐⭐ Hack 寫法 |
4. location.assign() | `location.assign(location.href)` | 標準導航 API,可被 `beforeunload` 攔截 | 全瀏覽器 | ⭐⭐⭐ 語意清晰 |
5. document.execCommand('Refresh') | `document.execCommand('Refresh')` | IE 專屬、已棄用 | IE only | ⭐ 不建議 |
6. window.navigate() | `window.navigate(location.href)` | IE 專屬、非標準 | IE only | ⭐ 不建議 |
7. location.replace() | `location.replace(location.href)` | 替換歷史記錄,**無法返回上一頁** | 全瀏覽器 | ⭐⭐ 特定場景 (登入後跳轉) |
8. document.URL = location.href | `document.URL = location.href` | 非標準、行為不可預期 | 部分瀏覽器 | ⭐ 避免使用 |
最佳實務
// 一般重新整理 (保留歷史、可回上頁)
location.reload();
// 強制從伺服器重載 (忽略快取)
location.reload(true);
// 登入成功導向,不想讓使用者按「上一頁」回登入頁
location.replace('/dashboard');
三、自動重新整理與導向
Meta 標籤 (無需 JS)
<!-- 20 秒自動重新整理 -->
<meta http-equiv="refresh" content="20">
<!-- 20 秒後導向指定網址 -->
<meta http-equiv="refresh" content="20;url=https://example.com">
JavaScript 定時器版 (可控制、可取消)
// 每 30 秒重新整理一次
var refreshTimer = setInterval(function () {
location.reload();
}, 30000);
// 單次延遲導向
setTimeout(function () {
location.href = 'https://example.com';
}, 5000);
// 可取消的自動重新整理元件
var AutoRefresh = {
timer: null,
start: function (intervalMs) {
this.stop();
this.timer = setInterval(function () { location.reload(); }, intervalMs);
},
stop: function () {
if (this.timer) clearInterval(this.timer);
}
};
// 使用: AutoRefresh.start(60000); // 1 分鐘
// 離開頁面時: window.addEventListener('beforeunload', () => AutoRefresh.stop());
四、框架/Iframe 跨框架重新整理
| 目標 | 代碼 | 備註 |
| 重新整理父視窗 | `parent.location.reload();` | 同源策略限制 |
| 子視窗重新整理父視窗 | `opener.location.reload();` | `window.open` 開啟的彈出視窗 |
| 重新整理同層 sibling iframe | `parent.frames['frameName'].location.reload();` | 或 `parent.iframeId.location.reload()` |
| 重新整理頂層視窗 | `top.location.reload();` | 跨域會拋 SecurityError |
體貼使用者的模式
<body onload="opener && opener.location.reload()"> <!-- 開窗即重新整理開啟者 -->
<body onunload="opener && opener.location.reload()"> <!-- 關窗時重新整理開啟者 -->
五、PHP / 伺服器端輸出重新整理腳本
<?php
// 重新整理父視窗
echo "<script>opener.location.reload();</script>";
// 重新整理開啟者並指定網址
echo "<script>opener.location.href = 'list.php';</script>";
// 關閉當前彈窗並重新整理父視窗
echo "<script>window.close(); opener.location.reload();</script>";
?>
六、JS 動態載入 JS (防重複載入)
function loadScript(url, callback) {
if (document.querySelector('script[src="' + url + '"]')) {
callback && callback();
return;
}
var script = document.createElement('script');
script.src = url;
script.onload = callback;
document.head.appendChild(script);
}
// 用法
loadScript('/scripts/swfobject-1.5.js', function () {
// SWFObject 已載入
});
七、常見坑點與避雷指南
- `history.back()` 在新分頁開啟時無效
- 新分頁歷史堆疊長度為 1,`back()` 無事發生。建議提供「關閉分頁」或「返回首頁」替代連結。
- `location.reload(true)` 仍讀到快取
- 伺服器需送出 `Cache-Control: no-cache, must-revalidate` 或 `ETag`/`Last-Modified` 驗證。
- 跨域 iframe 呼叫 `parent.location.reload()` 報錯
- 受同源策略限制。解法:父頁面監聽 `postMessage`,收到指定訊息自行 `location.reload()`。
- SPA 中 `history.pushState` 後使用者按 F5 導致 404
- 伺服器需配置 Fallback:所有非靜態資源請求導向 `index.html` (Nginx `try_files $uri $uri/ /index.html;`)。
- 行動裝置 `history.go(-1)` 觸發瀏覽器離開動畫而非邏輯返回
- 監聽 `popstate` 處理邏輯,而非依賴連結 `href="javascript:history.back()"`。
結語
歷史導航請優先使用標準 `history.back()/forward/go()`;重新整理首選 `location.reload([force])`;避免非標準 IE 專屬 API;跨框架操作必須同源;SPA 需配合伺服器 Fallback。掌握這張速查表,應對 99% 導航與重新整理場景綽綽有餘。