Explain Codes LogoExplain Codes Logo

How do I modify the URL without reloading the page?

javascript
prompt-engineering
history-api
browser-compatibility
Nikita BarsukovbyNikita Barsukov·Sep 19, 2024
TLDR

Utilize history.pushState() for a fresh history entry or history.replaceState() to modify the URL without creating a new entry.

history.pushState(null, '', '/new-path');

or

history.replaceState(null, '', '/new-path-no-history');

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.

// Checking if you've got a time machine if (window.history && window.history.pushState) { history.pushState({ detail: 'DeLorean' }, 'Title', '/back-to-future.html'); }

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:

// Mind the wormhole paradox! if (window.history && window.history.replaceState) { history.replaceState({ detail: 'Tardis' }, 'Changed Title', '/doctor-who.html'); }

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:

window.onpopstate = function(event) { // The TARDIS landed, where are we? if(event.state) { updatePageContent(event.state.detail); } };

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:

history.pushState({ page: 42 }, null, '?page=42'); // Hitchhiker's Guide anyone?

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:

history.replaceState({ step: 2 }, null, `?step=2`); // We're halfway there!

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:

if (history.state && history.state.id === 'unique-id') { history.replaceState(history.state, document.title, location.href); }

Retain unique states with a single history entry.