history.pushState()新增历史记录,适合导航跳转;replaceState()替换当前记录,适合修正URL而不留返回点;二者均需配合popstate监听及服务端配置防404。
浏览器原生的 history.pushState() 和 history.replaceState() 是操作历史记录的核心方法,但它们行为不同:前者在历史栈中新增一条记录,后者只替换当前记录,不增加长度。
常见错误是误用 pushState() 导致用户点「后退」时反复回到同一个空状态页(比如未正确设置 state 或 title);更隐蔽的问题是调用后未监听 popstate 事件,导致前进/后退时 UI 不更新。
pushState() 适合导航跳转(如点击菜单进入新页面视图)replaceState() 适合修正当前 URL 而不希望用户能退回(如表单提交后清理查询参数 ?step=2)state 必须是可序列化对象,不能传函数或 DOM 节点,否则触发 SecurityError
title 参数目前所有主流浏览器都忽略,可传空字符串 '' 避免歧义仅靠 popstate 事件不够——它不触发页面首次加载、也不响应 hashchange 或手动修改 location.href(非 push/replace 方式)。真实项目中必须组合处理。
关键点在于:首次加载时需主动读取 location.pathname 或 location.hash 初始化视图,不能等 popstate 触发;而后续导航才依赖事件驱动。
popstate:适用于 pushState/replaceState 引起的前进/后退hashchange:适用于基于 # 的简易路由(兼容旧浏览器)router.match(location.pathname)
removeEventListener 清理或用单例控制不需要 React Router 或 Vue Router,几行代码就能支撑 SPA 基础路由。核心是维护一个路由表 + 匹配函数 + 状态同步机制。
以下是一个仅处理路径前缀匹配的轻量实现,支持参数提取(如 /user/123 → {id: '123'}),已避开常见陷阱:
const router = {
routes: new Map(),
currentPath: location.pathname,
on(path, callback) {
this.routes.set(path, callback);
},
navigate(path) {
history.pushState({ path }, '', path);
this.currentPath = path;
this.resolve();
},
resolve() {
let matched = null;
for (const [routePath, handler] of this.routes) {
const keys = [];
const regex = new RegExp(`^${routePath.replace(/:(\w+)/g, (_, key) => {
keys.push(key);
return '([^/]+)';
})}/?$`);
const result = regex.exec(this.currentPath);
if (result) {
const params = Object.fromEntries(keys.map((key, i) => [key, result[i + 1]]));
matched = { handler, params };
break;
}
}
if (matched) matched.handler(matched.params);
}
};
// 初始化
window.addEventListener('popstate', e => {
router.currentPath = e.state?.path || location.pathname;
router.resolve();
});
// 使用示例
router.on('/user/:id', ({ id }) => {
document.getElementById('app').innerHTML = `User ${id}`;
});
router.on('/', () => {
document.getElementById('app').innerHTML = 'Home';
});
// 首次加载必须手动触发
router.resolve();
不要
以为用了 pushState 就万事大吉。真实部署时最常踩的坑是服务端配置缺失——当用户直接访问 /dashboard,服务器返回 404,因为没对应物理文件。
这不是前端能解决的问题,必须配合服务端或构建工具处理:
historyApiFallback: true
try_files $uri $uri/ /index.html; 规则vercel.json 或 _redirects 配置重写pushState 无法跨域,目标 URL 必须同源,否则抛 SecurityError
state 对象大小有限制(约 640KB),超限会静默失败路由不是加几个 pushState 就完事,URL 同步、服务端兜底、首次加载状态还原、浏览器前进后退一致性——每个环节断掉,用户都会看到白屏或错乱视图。