window.history 提供會話級瀏覽歷史操作能力。受限於同源策略,JS 無法讀取具體 URL 列表,但可通過 back()、forward()、go() 導航,配合 HTML5 History API (pushState/replaceState) 實現 SPA 路由核心邏輯。
// 後退
history.back(); // 等同於瀏覽器後退按鈕
history.go(-1); // 同義
// 前進
history.forward(); // 等同於瀏覽器前進按鈕
history.go(1); // 同義
// 任意跳轉
history.go(-2); // 後退兩步
history.go(2); // 前進兩步
history.go(0); // 刷新當前頁(等同 location.reload())
// 歷史記錄條數
console.log(history.length); // 當前會話歷史條數(含當前頁)
// 語法
history.pushState(stateObj, title, url);
// 示例:切換 Tab 無刷新改變 URL
$('.tab').click(function() {
var tabId = $(this).data('tab');
history.pushState({tab: tabId}, '', '?tab=' + tabId);
renderTab(tabId);
});
stateObj:任意可序列化對象,popstate 事件可取回。title:目前多數瀏覽器忽略,傳 '' 或 document.title。url:新 URL(相對/絕對),同源限制,不會觸發請求。// 登錄後替換登錄頁記錄,防止後退回登錄頁
history.replaceState({loggedIn: true}, '', '/dashboard');
window.addEventListener('popstate', function(event) {
// 用戶點擊瀏覽器後退/前進、調用 history.back/go 時觸發
// 注意:pushState/replaceState 不觸發 popstate
var state = event.state; // 對應 pushState 的 stateObj
if (state && state.tab) {
renderTab(state.tab);
} else {
// 初始加載或無 state,按 URL 解析
renderTab(getTabFromUrl());
}
});
class SimpleRouter {
constructor() {
this.routes = {};
window.addEventListener('popstate', this.onPopState.bind(this));
}
add(path, handler) {
this.routes[path] = handler;
}
navigate(path, state = {}) {
history.pushState(state, '', path);
this.routes[path]?.(state);
}
onPopState(e) {
var path = location.pathname + location.search;
this.routes[path]?.(e.state);
}
}
// 使用
const router = new SimpleRouter();
router.add('/home', () => renderHome());
router.add('/user/:id', (state) => renderUser(state.userId));
// 點擊鏈接攔截
$('a[data-link]').click(function(e) {
e.preventDefault();
router.navigate($(this).attr('href'));
});
history 具體 URL 列表(防止歷史洩露)。pushState URL 必須同源(協議/域名/端口一致)。| 問題 | 原因 | 解決 |
|---|---|---|
| 後退不刷新頁面 | 瀏覽器 bfcache (Back-Forward Cache) | 監聽 pageshow 事件 event.persisted 判斷 |
| pushState 後刷新 404 | 服務端未配置 fallback 到 index.html | Nginx/Apache 配置 try_files $uri $uri/ /index.html |
| state 對象序列化失敗 | 包含函數/循環引用/DOM 元素 | 只存純數據 (JSON 可序列化) |
history.back/forward/go 適用於簡單導航;pushState/replaceState + popstate 是 SPA 路由、無刷新換頁、瀏覽器前進後退同步狀態的基石。理解 bfcache、服務端 fallback、state 序列化限制,能避開 90% 的歷史管理坑點。