How to change the URL of a webpage without reloading using Javascript?

March 11, 2021 - 2 min read

To change the URL of the webpage without reloading, you can use the replaceState() method in the global window.history object in JavaScript.

/* Change URL without reloading webpage 📝*/
window.history.replaceState({}, "", "/new-url/hello");
  • The first argument is of an object type, where you can define some states you need to about the current URL.
  • The second argument is of a string type to change the title of the webpage (or the name that should be shown in the tab of the browser), but nowadays most browsers will ignore this argument. So we are passing an empty string.
  • The third argument is of a string type where we change the URL without reloading the webpage.

For example,

Let's say our URL was https://melvingeorge.me/blog/hello-world-blog before changing like this,

Now let's use the replaceState() method to change the url to https://melvingeorge.me/info. It can be done like this,

// Change URL to /info
window.history.replaceState({}, "", "/info");

/*
    RESULT: https://melvingeorge.me/info
*/

Now the URL looks like this,

Now the URL is changed. Yay! 🥳

🔴 NOTE: You can change the URL of your current origin only. You cannot change the complete URL to a different domain name like https://www.google.com/search.

// 🛑 This won't work if you are in melvingeorge.me website
// The method will throw an error here
window.history.replaceState({}, "", "https://www.google.com/search");

// You need to be on the google.com website to do this

Play with code in Codesandbox.

Feel free to share if you found this useful 😃.