DEV Community

Cover image for How to change the URL of a webpage without reloading using Javascript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

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

Originally posted here!

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");
Enter fullscreen mode Exit fullscreen mode
  • 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,

before url is changed

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
*/
Enter fullscreen mode Exit fullscreen mode

Now the URL looks like this,

after url is changed

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
Enter fullscreen mode Exit fullscreen mode

Play with code in Codesandbox.

Feel free to share if you found this useful ๐Ÿ˜ƒ.


Top comments (0)