我有一个 3 步注册过程,其中每个步骤都使用 JavaScript 显示在页面上,无需刷新页面。我现在想做的是添加一个向后引用来指示用户所处的步骤,这样如果他们单击浏览器后退按钮,他们就不会丢失所有进度。
例如,当用户从步骤 2 导航到步骤 3 时,URL 保持在 www.example.com。然后用户单击浏览器后退按钮。 URL 现在应该是 www.example.com?step-2.
我想我会以某种方式需要使用 History API 来完成此任务,但如果我使用 window.history.pushState(null, null, 'www.example.com?step-2'),当前 URL 将是也变了。
如何在不更改当前 URL 的情况下完成添加到历史记录?
如果您的目标是不更改 URL,但仍允许来回历史状态更改,那么最好的选择是利用窗口的
hashchange
事件侦听器。这当然会利用 URL 中的哈希引用,但基本 URL 不会改变:
function locationHashChanged() {
if (location.hash === '#step-2') {
// Do something here
}
}
window.onhashchange = locationHashChanged;
有关这方面的更多信息,请参阅官方文档: https://developer.mozilla.org/en-US/docs/Web/API/Window/hashchange_event
幸运的是,这个问题有一个简单直接的解决方案,即利用
pushState
方法。
我们只需要使用 pushState
方法中经常被忽视的
state参数即可。
通过这样做,我们可以在更新状态参数时在浏览器的会话历史记录中插入一个条目,而无需更改 URL(推送相同的 URL)。
// Retrieve your URL parameters
const urlParams = getParams();
// Retrieve current URL
const currentUrl = window.location.pathname;
// Update the browser's session history
window.history.pushState({ urlParams }, '', currentUrl);
请记住,每当用户向前/向后导航时,就会触发
popstate
事件。 popstate
事件有一个状态属性,指向历史条目的状态对象。
function handlePopState(event) {
if (event.state?.urlParams) {
const restoredParams = event.state.urlParams;
// Now you can use the restoredParams object as needed
console.log('Restored URL params:', restoredParams);
}
}
// Add an event listener for the popstate event
window.addEventListener('popstate', handlePopState);