js实现回退
使用 history.back()
history.back() 方法模拟浏览器的后退按钮,返回到上一个访问的页面。这是最直接的回退方式。
// 点击按钮触发回退
document.getElementById('backButton').addEventListener('click', function() {
history.back();
});
使用 history.go()
history.go() 方法允许更灵活地控制历史记录导航。传递参数 -1 等同于 history.back(),传递 -2 则回退两页。

// 回退一页
history.go(-1);
// 回退两页
history.go(-2);
使用 window.location.href
通过修改 window.location.href 可以手动指定回退的页面。适用于需要精确控制目标页面的场景。

// 返回到指定页面
window.location.href = document.referrer;
监听浏览器后退事件
通过 popstate 事件可以监听浏览器的后退操作,适用于需要在回退时执行额外逻辑的场景。
window.addEventListener('popstate', function(event) {
console.log('回退操作触发');
});
使用框架或库
在 Vue、React 等框架中,通常使用其路由库(如 vue-router 或 react-router)实现回退功能。
Vue Router
// 在 Vue 组件中
this.$router.go(-1);
React Router
// 在 React 组件中
import { useNavigate } from 'react-router-dom';
function BackButton() {
const navigate = useNavigate();
return <button onClick={() => navigate(-1)}>返回</button>;
}
注意事项
- 如果历史记录中没有前一页,
history.back()和history.go(-1)不会产生任何效果。 document.referrer可能为空,需检查其值是否有效。- 在单页应用(SPA)中,优先使用框架提供的路由方法。






