History、状态与单页导航
back/forward/go 操作历史,pushState/replaceState 修改当前会话历史状态。本章结合代码、对比实例、边界检查和练习说明具体用法。
back/forward/go 操作历史,pushState/replaceState 修改当前会话历史状态。
学完这一章,你能够
- 概念与基本规则
- 用法、结果与边界
- 现代项目中的选择
概念与基本规则
back/forward/go 操作历史,pushState/replaceState 修改当前会话历史状态。
用法、结果与边界
pushState 本身不会触发 popstate;前进后退等历史遍历会触发相关事件。状态需要可序列化且地址受同源限制。
现代项目中的选择
根据目标环境检查接口与行为;本例避免自动改变浏览器设置、历史或持久身份数据。
pushState、replaceState 与事件
以下代码供真实同源路由使用,不由当前示例自动执行。pushState 增加会话历史,replaceState 替换当前条目;前进后退时通过 popstate 恢复视图。
服务器仍需支持对应地址的直接访问和刷新。路由更新还应同步标题、主要内容和适当的焦点,不只改变地址栏。
// 在真实同源页面中使用:
const next = new URL(location.href);
next.searchParams.set("page", "2");
history.pushState({ page: 2 }, "", next);
window.addEventListener("popstate", event => {
console.log("恢复视图状态", event.state);
});
操作:会话历史与路由恢复
back/forward/go 在已有条目间移动,pushState/replaceState 只改变历史和地址,不自动获取或渲染页面。
事件:会话历史与路由恢复
后退前进可触发 popstate,pushState 本身不等于触发它;恢复界面需从 state 或地址重建。
服务器:会话历史与路由恢复
深层地址刷新仍需正确响应,同源限制不可忽略;切换页面同步标题、内容及合适焦点。
真正创建历史条目,再后退和前进
back和forward分别遍历到当前会话历史的前一项、后一项,等价于go(-1)和go(1);没有相应条目时不会凭空生成页面。它们异步发起遍历,返回undefined,不能把返回值当成导航完成结果。历史API不允许枚举用户所有访问地址。
pushState添加同源历史条目但不取新页面,也不自行触发popstate;replaceState替换当前条目。真正遍历时监听popstate恢复页面,URL变化不代表内容已经自动更新。状态要可序列化,目标地址须符合来源限制。
本例仅点击初始化后建立带专用状态标记的练习条目,使用当前真实文件的查询串,避免访问不存在的文件。后退/前进按钮限制在本次练习已创建的范围,演示历史状态、事件次数和正文标题同步。隔离预览应改用独立同源HTTP页。
history.pushState({step:1}, "", "?lesson-step=1");
// pushState不会自动触发popstate。
addEventListener("popstate",event=>render(event.state));
// 用户操作后:history.back(); history.forward();
尝试一下 ↗ 在独立页面修改并运行
本章方法、参数与返回值
方法与属性分别辨认;可选参数的省略值按具体接口定义,不统一理解为 null 或 0。异步完成、同步返回和错误回调是不同阶段。
| 方法 / 成员 | 参数 | 返回值 / 值 | 说明与边界 |
| history.back() / forward() | 无 | undefined | 取决于已有会话历史。 |
| history.go(delta) | 相对步数 | undefined | 不凭返回值判断导航成功。 |
| pushState(state, unused, url) | 可序列化状态、空字符串、可选同源 URL | undefined | 不自动获取或渲染页面。 |
| replaceState(state, unused, url) | 状态、空字符串、可选同源 URL | undefined | 替换当前条目,另处理 popstate 恢复。 |
核心代码与完整实例
<main><p>蓝色天空网 · mbsky.com · 学习与实践</p><h1>真正创建历史条目,再后退和前进</h1><button type="button" id="history-init">初始化本页历史练习</button><button type="button" id="history-add" disabled>添加下一步</button><button type="button" id="history-back" disabled>后退一步</button><button type="button" id="history-forward" disabled>前进一步</button><h2 id="step-title">尚未初始化</h2><output id="result">请独立打开本例,再初始化。</output></main>
<script>
const output=document.querySelector("#result"),add=document.querySelector("#history-add"),back=document.querySelector("#history-back"),forward=document.querySelector("#history-forward");let token=null,current=0,max=0,events=0,busy=false;const initialTitle=document.title;function render(){document.querySelector("#step-title").textContent="当前练习步骤:"+current;document.title=initialTitle+" · 步骤"+current;add.disabled=busy;back.disabled=busy||current===0;forward.disabled=busy||current===max;output.textContent=JSON.stringify({step:current,maxStep:max,popstateEvents:events,url:location.href},null,2);}document.querySelector("#history-init").addEventListener("click",()=>{try{if(!/^https?:$/.test(location.protocol))throw new Error("请在独立HTTP/HTTPS页面验证真实历史。");if(token){output.textContent="本页已初始化,请继续现有练习。";return;}const nextToken=String(Date.now());history.replaceState({mbskyHistoryDemo:nextToken,step:0},"",location.href);token=nextToken;render();}catch(error){output.textContent=error.name+":"+error.message;}});add.addEventListener("click",()=>{if(!token||busy)return;try{const next=current+1,url=new URL(location.href);url.searchParams.set("lesson-step",String(next));history.pushState({mbskyHistoryDemo:token,step:next},"",url);current=next;max=next;render();}catch(error){output.textContent=error.name+":"+error.message;}});back.addEventListener("click",()=>{if(!token||busy||current===0)return;busy=true;render();history.back();});forward.addEventListener("click",()=>{if(!token||busy||current===max)return;busy=true;render();history.forward();});window.addEventListener("popstate",event=>{if(event.state?.mbskyHistoryDemo!==token){busy=false;add.disabled=back.disabled=forward.disabled=true;output.textContent="已离开本次练习状态,请重新载入后初始化。";return;}current=event.state.step;events++;busy=false;render();});
</script>
初始化步骤0;添加到1、2但事件数仍0;后退到1事件数加1,前进到2再加1;没有创建的范围按钮不可用。
本章附件与实例包
常见错误与边界检查
| 常见问题 | 检查与改进 |
|---|---|
| 需要特别注意 | 不能把地址栏变了当作服务端已能处理该路径。 |
技术规范与官方资料
练习与参考解答
先预测示例结果,再修改一个输入,说明变化的原因。
查看参考解答
逐条比较输入、类型和输出;根据本节规则解释差异,而不只记录最终画面。