History Pushstate Updates Url Without Reload

history.pushState changes the address bar and stores view state without reloading, and popstate hands that state back on back and forward.

JavascriptData Fetching

Code

javascriptsnippet
18 lines
// 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 ?? '');
}

What the code does

History Pushstate Updates Url Without Reload is built around the function render.

Points of care

  • Uses document, window, so it needs a browser context — it will not run as-is in Node without shims.

Using it

Signature: function render(view, id)

The demo output is labeled (render:), so every printed line maps back to its originating operation.

Key statements

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');
}
});

Interactive Tools for This Topic

FAQ

Does History Pushstate Updates Url Without Reload run in plain Node.js?
No — it touches `document` and `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.