js 实现后退
使用 window.history.back()
window.history.back() 方法用于返回到浏览器历史记录中的上一页,相当于用户点击浏览器的后退按钮。这是最直接的方式。
window.history.back();
使用 window.history.go()
window.history.go() 方法允许通过传递一个整数参数来导航历史记录。传递 -1 表示后退一页。

window.history.go(-1);
监听按钮点击事件
在 HTML 中绑定按钮点击事件,触发后退操作。
<button id="backButton">返回</button>
<script>
document.getElementById('backButton').addEventListener('click', function() {
window.history.back();
});
</script>
检查历史记录长度
在调用后退方法前,可以检查历史记录长度,确保有可返回的页面。

if (window.history.length > 1) {
window.history.back();
} else {
console.log('没有可返回的页面');
}
结合路由库(如 React Router)
在使用前端路由库时,后退操作可能需要调用路由提供的方法。例如,在 React Router v6 中:
import { useNavigate } from 'react-router-dom';
function BackButton() {
const navigate = useNavigate();
return <button onClick={() => navigate(-1)}>返回</button>;
}
使用 document.referrer
如果需要返回上一页的 URL,可以通过 document.referrer 获取上一页地址,然后手动跳转。
if (document.referrer) {
window.location.href = document.referrer;
} else {
console.log('没有可返回的页面');
}






