How do I modify the URL without reloading the page?
Utilize history.pushState()
for a fresh history entry or history.replaceState()
to modify the URL without creating a new entry.
or
null
denotes an empty state object, followed by a title placeholder parameter (commonly empty) and finally the new URL.
JavaScript History API: pushState and replaceState Explained
pushState()
Function for URL Changes
The history.pushState()
function allows developers to navigate changing URLs without causing a page reload, this is especially critical for Single Page Applications (SPAs). This function makes an entry to the browser's history hence enabling natural page navigation.
Above, we perform a browser compatibility check and update the URL, maintaining the state (and the flux capacitor) of the application.
The Usefulness of replaceState()
Sometimes, we don't want an extra history entry. Here, history.replaceState()
provides a tool to change the current URL without creating a new history entry:
This is particularly useful in updating URLs in response to filters or search criteria where unnecessary history entries should be avoided.
Harnessing onpopstate
for Navigation
window.onpopstate
is triggered when the active history entry changes. This is essential for interactive pages:
The consequence? The page content materializes to match the backward or forward navigation performed by your companions.
Mastering Browser History Manipulation
Crafting Intuitive URLs
Unlike traditional hashed (#
) URLs, history.pushState()
enables developers to create clean, SEO-friendly URLs. Boost your user experience by making URLs clear and user-friendly.
Avoiding refreshes
Steer away from document.location
or window.location.href
as they prompt complete page refreshes. Instead, history.pushState()
or history.replaceState()
, lead to a seamless user experience.
Handling potential threats
Beware of potential URL misrepresentation. Restrictions should be placed within the same domain for security and Same-Origin Policy compliance.
Remembering history
Support page state changes without modifying history by using history.replaceState()
. Provide advanced functionality without littering unnecessary history entries.
Practical Use Cases of History API
SPAs And Dynamic Content Loading
In Single-Page Applications, URL changes can be linked to dynamic content loading:
Create a new history entry for navigation and load relevant content without refreshing.
Multi-step Forms Progress Tracking
For multi-step forms, you can use replaceState
to keep the URL updated:
Each form step is reflected in the URL, empowering users to save or share their progress.
Preventing Duplicate History Entries
Avoid bloating of duplicate history that happens from revisiting the same state:
Retain unique states with a single history entry.
Was this article helpful?