history.pushState()在历史栈新增记录,replaceState()直接替换当前记录;两者均不刷新页面,参数相同且URL须同源;需监听popstate响应导航,并配置服务端fallback避免404。
两者都用于修改浏览器地址栏而不触发页面刷新,但 pushState() 会在历史栈中新增一条记录,用户点击后退会回到上一个状态;replaceState() 则直接替换当前历史记录,不增加新条目——这对表单提交后避免重复提交、或修正 URL 参数特别有用。
pushState() 适合导航跳转:比如从 /home 切到 /profile
replaceState() 适合微调当前页:比如搜索框输入时实时更新 URL 中的 q=xxx,但不想
让用户多按几次后退才退出搜索页state 对象(可存任意 JSON-serializable 数据),第二个是标题(多数浏览器忽略),第三个才是关键的 url(必须同源)url 不会触发请求,但必须是相对路径或同源绝对路径,否则抛出 SecurityError
用户点击浏览器前进/后退按钮,或调用 history.back() 时,会触发 popstate 事件。注意:它只在历史记录切换且 state 非空时触发(pushState({}) 或 replaceState(null, '', url) 不会触发)。
window.addEventListener('popstate', handler) 注册,不能靠 onpopstate 属性event.state 就是当时 pushState() 或 replaceState() 传入的 state 对象popstate,需手动读取 history.state 并初始化视图window.addEventListener('popstate', (e) => {
if (e.state) {
renderView(e.state.page); // 比如渲染 'home' 或 'settings'
}
});
// 页面加载后也要检查初始 state
if (history.state?.page) {
renderView(history.state.page);
}
单页应用所有路由都由前端接管,但用户直接访问 /settings 或刷新页面时,浏览器会向服务端发起请求。如果服务端没配置,就返回 404。这不是 JS 能解决的问题,必须后端配合。
historyApiFallback: true 自动返回 index.html
try_files $uri $uri/ /index.html; 到 location 块app.use(express.static('dist')) 后,再加 app.get('*', (req, res) => res.sendFile(path.join(__dirname, 'dist', 'index.html')))
location.pathname 做真实路由分发不要直接用 location.pathname 做字符串比对,尤其当应用部署在子路径(如 https://example.com/my-app/)时,pathname 是 /my-app/settings,而你的路由定义可能是 /settings。
new URL(location.href).pathname 更可靠,但依然要处理 base hrefbasename 截断:比如已知应用挂载在 /my-app,则 const path = location.pathname.replace(/^\/my-app/, '') || '/'
/^\/settings\/?$/ 比 /^\/settings$/ 更容错/user/123)建议用 URLPattern(Chrome 110+)或轻量库如 path-to-regexp,避免手写正则出错真正麻烦的从来不是 pushState 怎么调,而是怎么让 URL 变化、视图更新、服务端不报错、子路径不崩、参数解析不漏——每个环节都卡在边界 case 上。