js实现回退
使用 window.history 回退
通过 window.history.back() 方法实现返回上一页,等同于浏览器后退按钮的功能。
window.history.back();
监听回退按钮事件
通过 popstate 事件监听浏览器后退/前进操作,可在用户手动触发后退时执行自定义逻辑。

window.addEventListener('popstate', function(event) {
console.log('回退操作触发');
// 自定义逻辑
});
使用 history.go() 控制回退步数
history.go(-1) 返回上一页,history.go(-2) 返回前两页,依此类推。

window.history.go(-1); // 回退一步
单页应用(SPA)路由回退
若使用 react-router 或 vue-router,可通过路由提供的导航方法实现回退:
- React Router v6:
import { useNavigate } from 'react-router-dom'; const navigate = useNavigate(); navigate(-1); // 回退一步 - Vue Router:
this.$router.go(-1); // 回退一步
强制重定向替代回退
若需避免用户返回某些页面(如登录后),可用 window.location.replace 替换历史记录:
window.location.replace('/home'); // 当前页被替换,无后退记录
注意事项
history.back()和history.go()受同源策略限制,无法跨域操作。- 单页应用需确保路由堆栈管理正确,避免多次回退导致意外跳转。






