Change the URL Without Reloading the Page Using JavaScript

Sometime you might have the need to change the URL of your website without reloading the entire page. This might be the case if you dynamically load content via AJAX according to user input and want to preserve the current website state in the URL.

It is possible in modern browsers to update the URL without reloading the page using the pushState() function of the History API.

You can implement the change of URL with one line of code

window.history.pushState("object or string", "Page Title", "/newURL");

This line of code will change the current URL to www.your-domain.com/newURL (3rd parameter) and change the title to Page Title (2nd parameter). It will also add a new state, which means by using the “Back Button” of your browser you can return to the previous page.

If you do not want this you can use the following function which will override the current state. You will not be able to use the back button to return to the previous page.

window.history.replaceState("object or string", "Page Title 2", "/newURL2");

Which Browsers Support this Feature?

Not all browsers support this feature. However, the most modern browsers will support it. These include

  • IE 10+
  • Edge
  • Firefox 4+
  • Chrome 5+
  • Safari 6+
  • Opera 11.5+

For the other browsers you can redirect the page to the new URL using document.location.href, which will however trigger a reload of the page. You can use the following code snippet:

if (history.pushState) {
    window.history.pushState("object or string", "Page Title", "/newURL");
} else {
    document.location.href = "/newURL";
}