推荐使用 localStorage 记录用户最后一次访问的页面路径,通过 window.location.pathname + window.location.search 获取并保存路径,读取后安全跳转,并在登出等场景及时清理。

可以使用 localStorage 或 sessionStorage 来记录用户最后一次访问的页面路径(URL),实现“返回上次位置”或“自动跳转到上次浏览页”的功能。推荐用 localStorage,因为它持久保存,关闭浏览器也不丢失。
获取并保存当前访问路径
在页面加载时,读取当前 URL 的路径部分(如 /product/detail?id=123),然后存入 localStorage:
- 用
window.location.pathname + window.location.search获取干净的路径+查询参数 - 避免保存完整 URL(含协议、域名),便于跨环境复用
- 示例代码:
localStorage.setItem('lastVisitPath', window.location.pathname + window.location.search);
在需要时读取并跳转
比如在首页按钮点击、登录后重定向、或页面初始化时恢复位置:
- 用
localStorage.getItem('lastVisitPath')获取值 - 检查是否为空或是否为有效路径(可简单判断是否以
/开头) - 安全跳转:
if (path) window.location.href = path;
注意清理过期或无效记录
用户登出、清除偏好、或访问了不可再进入的页面(如支付完成页)时,应主动清除:
- 登出时调用
localStorage.removeItem('lastVisitPath') - 可选:监听
beforeunload事件做条件性保存(如仅保存非登录/注销类路径) - 避免把敏感路径(如
/user/settings)暴露给未登录用户
替代方案:结合 history.state 更精细控制
若需记录更丰富的上下文(如滚动位置、表单草稿),可配合 history.pushState() 和 popstate 事件,但 localStorage 仍是最轻量、兼容性最好的基础方案。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










