How do I modify the URL without reloading the page?
You can modify the browser’s URL without triggering a page reload using the History API. Below are the main methods:
-
history.pushState()
Adds a new entry to the browser’s session history stack.history.pushState({ key: 'value' }, '', '/new-url');
- State Object: Pass any serializable object to track additional data.
- Title: Most browsers ignore this parameter, so a blank string is common.
- URL: The new displayed URL. Must be same-origin (same domain/port/protocol).
-
history.replaceState()
Replaces the current history entry, rather than adding a new one.history.replaceState({ key: 'value' }, '', '/another-url');
- Ideal for updating the URL without increasing the user’s “Back” history stack.
-
location.hash
Modifying the URL hash won’t reload the page (unless you’re linking to an anchor in the same page). For example:location.hash = 'section2';
- Easiest approach if you only need to change or add
#
fragments. - Not as flexible as the History API for clean, non-hash URLs.
- Easiest approach if you only need to change or add
Example usage with the History API:
document.querySelector('#changeUrlBtn').addEventListener('click', () => { history.pushState({ updated: true }, '', '/newSection'); // The displayed URL changes to '/newSection' without reloading. });
Notes:
- After using
pushState()
orreplaceState()
, you can listen for the popstate event to handle backward/forward navigation. - Avoid cross-origin URLs (
http://anotherdomain.com/...
), as browsers prevent tampering with the address to different domains.
Level Up Your JavaScript Skills
If you want to explore more about DOM manipulation, events, and best practices for single-page applications (SPA), consider these courses on DesignGurus.io:
They combine practical examples with conceptual depth, helping you become more confident in creating dynamic, seamless web experiences without unnecessary page reloads.