← 中文资源

简体中文版本

history.pushState 更新地址栏而不刷新

pushState 只改地址栏 URL 并压入一条历史记录,页面不重载;popstate 在后退/前进时把存的 state 交回来,视图状态随 URL 一起可恢复。

阅读英文原文

实现说明

history.pushState 更新地址栏而不刷新的核心是函数 render。

使用要点

  • 用到了 document、window,需要在浏览器环境运行,Node 里直接跑会缺 API。
  • 每一步打印都带着自己的标签:render:。

常见问题

「history.pushState 更新地址栏而不刷新」能在裸 Node.js 里跑吗?

不能——document、window 的家在浏览器里,Node 进程提供不了。执行时请用页面(或 DevTools 控制台)。

签名一览:function render(view, id)

核心语句

document.querySelector('#open-inbox').addEventListener('click', () => {
  history.pushState({ view: 'inbox', id: 42 }, '', '/inbox/42');
  render('inbox', 42);
});
window.addEventListener('popstate', (event) => {
  if (event.state?.view === 'inbox') {
    render('inbox', event.state.id);
  } else {
    render('home');
  }
});

代码示例

// pushState 只改地址栏 URL(no reload)并新增一条历史记录
document.querySelector('#open-inbox').addEventListener('click', () => {
  history.pushState({ view: 'inbox', id: 42 }, '', '/inbox/42');
  render('inbox', 42);
});

// popstate:用户点后退/前进时拿到之前存的 state,用它恢复视图
window.addEventListener('popstate', (event) => {
  if (event.state?.view === 'inbox') {
    render('inbox', event.state.id);
  } else {
    render('home');
  }
});

function render(view, id) {
  console.log('render:', view, id ?? '');
}