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.
Code
// 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
Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.Nano ID GeneratorGenerate URL-safe Nano ID strings with a configurable length and alphabet using the Web Crypto API.Query String ParserParse a query string or URL into decoded key-value rows, preserving repeated keys and empty values for debugging and API work.URL Slug GeneratorCreate readable URL slugs from titles and phrases with accent removal, configurable separators, and a maximum length while preserving Unicode letters.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.