JavaScript Answers

How to update the page title when using history.replaceState() with JavaScript?

Spread the love

To update the page title when using history.replaceState() in JavaScript, you can update both the URL and the title simultaneously.

To do this we write:

// New page title
var newTitle = "New Page Title";

// New URL (optional)
var newUrl = "/new-url"; // Replace with your desired URL

// Update the page title
document.title = newTitle;

// Update the URL and page title using history.replaceState()
history.replaceState(null, newTitle, newUrl);

In this example, newTitle is the new title you want to set for the page.

newUrl is the new URL you want to replace the current URL with. This parameter is optional; if you don’t want to change the URL, you can pass null.

history.replaceState() updates the current history entry with the new URL and title, effectively replacing the current state in the browser’s history without creating a new entry.

By setting document.title before calling history.replaceState(), you ensure that the new title is reflected in the browser’s UI and tab title.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *