Write an article or Share a link

How To Change URL Without Reloading Page Using Javascript

Hints Staff
4 years ago
How To Change URL Without Reloading Page Using Javascript  by html hints

Got many queries regarding How to change URL without refreshing the browser. In this article, we are looking into updating the URL by use of the History API to access and modify the URL states.

#

JavaScript History API

The history API is a set of methods used to manipulate history. For instance, we can go forward and backward, just like clicking the buttons in your browser.

#

JavaScript window.history.pushState

We can use this method to push a new entry into the browser's history. It doesn't need a refresh and will show the new URL in the browser.

The window.history.pushState() method accepts three arguments:

state: This is an object with details about the URL

title: The title (normally the <title> attribute)

url: The actual URL you see in your browser bar.


    window.history.pushState('NewPage', 'Title', '/new-page');
                

You can try this live by copy above code & open console and paste this code over their. You will see result by your own.

To make it Dynamic, you can easily make it by using function.


    function processAjaxData(response, url){
      document.getElementById("content").innerHTML = response.html;
      document.title = response.Title;
      window.history.pushState({"html":response.html,"Title":response.Title},"", url);
    }
                

Above code will take two parameters dynamically & you can manipulate it according to your use.

We use cookies to ensure better User Experience. Read More