Member-only story
How do I use JavaScript to modify the URL without reloading the page? history.pushState()
or history.replaceState()
2 min readNov 11, 2022
Topic Covered:
using History API (pushState or replaceState) or Location API (href or assign or replace)
Using the History API
- You can use either
history.pushState()
orhistory.replaceState()
to modify the URL in the browser - The arguments for both methods are the same, allowing you to pass a customized serializable
state
object as the first argumen
// Current URL: https://my-website.com/page_a
const nextURL = 'https://my-website.com/page_b';
const nextTitle = 'My new page title';
const nextState = { additionalInformation: 'Updated the URL with JS' };
// This will create a new entry in the browser's history, without reloading
window.history.pushState(nextState, nextTitle, nextURL);
// This will replace the current entry in the browser's history, without reloading
window.history.replaceState(nextState, nextTitle, nextURL);
Using the Location API
- It reloads the page, but still allows you to modify the current URL and might be useful when working with legacy browsers. You can modify the URL, using either
Window.location.href
,location.assign()
orlocation.replace()
:
// Current URL: https://my-website.com/page_a
const nextURL = 'https://my-website.com/page_b';
// This will create a new entry in the browser's…