Explain Codes LogoExplain Codes Logo

History.replacestate() example?

javascript
history-api
browser-terrain
cross-browser-inconsistencies
Alex KataevbyAlex Kataev·Dec 31, 2024
TLDR

Invoke history.replaceState() to modify the browser’s URL and associated state without reloading the page or adding a history entry - perfect for AJAX navigation in single-page apps.

Usage:

// The URL changes to "updated-page.html", but thankfully our page doesn't reload // Hmmmmm. magic? No, it's JavaScript 👀 history.replaceState({ detail: 'update' }, '', 'updated-page.html');

Key Point: The URL bar updates to updated-page.html, no page reload. The state object ({ detail: 'update' }) is a tracker for changes within the same webpage.

But beware, history.replaceState() won't update the document title. So, to set a new title, tweak document.title as necessary:

Title Update Example:

// No worries - we've got your title covered document.title = 'Updated Page Title'; history.replaceState({ detail: 'update' }, 'Updated Page Title', 'updated-page.html');

Every browser has its own character, and they don't all play nice with the title parameter in replaceState() and pushState(). Time to navigate these terrain.

Surviving Cross-Browser Inconsistencies

Before you deploy, validate your code across different browsers to avoid nasty surprises - remember, replaceState() behaves distinctively on platforms like Chrome or Opera.

Renewing Document Title

To change the page title, make sure Santa is not watching:

// You didn't see anything, Santa document.getElementsByTagName('title')[0].innerHTML = 'New Title';

Backtracking Navigation Changes

Implement a listener on window.onpopstate to act upon history navigation changes pending:

// Wait, did someone press the back button? window.onpopstate = function(event) { if (event.state) { updateContent(event.state.detail); } }; function updateContent(detail) { // Add your logic to update the content here }

Dodging AJAX Potholes

replaceState() along with AJAX spice things up - you can fetch and display new content without making the user wait for a page reload.

// Let's surprise the user with some new content function loadContent(url) { // Fetch the content, then use replaceState to update the URL without a page refresh fetch(url) .then(response => response.text()) .then(html => { document.getElementById('content').innerHTML = html; history.replaceState({ content: html }, '', url); }); }

And if you're on the jQuery team, it's got you covered for a smoother AJAX content handling with pushState and popstate.