HTML5 History API 讓單頁應用 (SPA) 在**不重新載入頁面**的情況下,操作瀏覽器歷史堆疊、更新網址列、響應前進/後退。本文系統講解核心 API、事件模型、實戰路由模式、SEO 與伺服器端配合要點。
| 方法/事件 | 用途 | 參數 |
|---|---|---|
history.pushState(state, title, url) | **新增**一筆歷史記錄 | state: 任意可序列化物件 (popstate 取回) title: 目前多數瀏覽器忽略,傳 '' 或 null url: 相對/絕對 URL,更新網址列但**不重載** |
history.replaceState(state, title, url) | **替換**當前歷史記錄 | 參數同 pushState,不增加堆疊長度 |
history.go(delta) | 前進/後退 (負數後退) | delta: 整數 |
history.back() / forward() | 等同 go(-1)/go(1) | -- |
popstate 事件 | **使用者點擊瀏覽器前進/後退、或呼叫 go/back/forward** 時觸發 | event.state = 對應的 state 物件 |
// 假設當前歷史堆疊: [A]
history.pushState({page:1}, '', '/page1'); // 堆疊: [A, page1] 長度+1
history.pushState({page:2}, '', '/page2'); // 堆疊: [A, page1, page2] 長度+1
history.replaceState({page:2b}, '', '/page2b'); // 堆疊: [A, page1, page2b] 長度不變
history.back(); // 觸發 popstate, state={page:1}, URL=/page1
history.forward(); // 觸發 popstate, state={page:2b}, URL=/page2b
history.go/back/forward、**不包含** pushState/replaceState 呼叫瞬間。event.state:對應目標歷史項的 state 物件 (若無則為 null)。load 後觸發一次 popstate (state=null);Firefox/IE 不觸發。需統一處理:let initialPop = true;
window.addEventListener('popstate', e => {
if (initialPop) { initialPop = false; return; } // 忽略首次
handleRoute(e.state, location.pathname);
});
// 簡易路由器 (無依賴)
class Router {
constructor() { this.routes = new Map(); }
add(path, handler) { this.routes.set(path, handler); }
navigate(path, state = {}) {
history.pushState(state, '', path);
this.dispatch(path, state);
}
replace(path, state = {}) {
history.replaceState(state, '', path);
this.dispatch(path, state);
}
start() {
window.addEventListener('popstate', e => this.dispatch(location.pathname, e.state));
this.dispatch(location.pathname, history.state);
}
private dispatch(path, state) {
const handler = this.routes.get(path) || this.routes.get('*');
handler?.(state, path);
}
}
// 使用
const router = new Router();
router.add('/', () => renderHome());
router.add('/detail/:id', (state, path) => renderDetail(path.split('/')[2], state));
router.add('*', () => render404());
router.start();
// 點擊攔截 (委派)
document.body.addEventListener('click', e => {
const a = e.target.closest('a[href^="/"]');
if (a && !a.hasAttribute('target') && !e.metaKey && !e.ctrlKey) {
e.preventDefault();
router.navigate(a.pathname);
}
});
**刷新/直接訪問 /detail/123 時,伺服器必須回傳同一份 index.html**,讓前端路由接管。否則會 404。
try_files $uri $uri/ /index.html;FallbackResource /index.htmlapp.get('*', (req,res)=>res.sendFile('index.html'))<title>, <meta name="description">, og:*, twitter:* (用 react-helmet/vue-meta/原生 document.head.append)。sitemap.xml 列出所有路由。hashchange、或在 pushState 後手動觸發 dispatchEvent(new PopStateEvent('popstate')) (不需手動觸發)。History API 是 SPA 路由基石,配合伺服器回退規則與狀態管理,能打造媲美多頁應用的瀏覽體驗。