Replacing the current state with replaceState() Method

  • The history interface of the browser manages the browser session history. It includes the page visited in the tab or frame where the current page is located. Manipulating this state can be used to change the URL of the browser without reloading the page.
  • The replaceState() method is used to modify the current history entry and replace the properties of the state with ones in the passed parameters.
  • The parameters of this method have 3 parts, the state object which is a serializable object about the state, the title which is the title of the new state, and the URL which is the new URL of the state.
  • The URL can be changed by passing the required URL as a string to this method. This will change the URL of the page without reloading the page.

Example: In this example, we have used the replaceState() method.

html




<!DOCTYPE html>
<html>
 
<head>
    <title>
        How to modify URL without reloading
        the page using JavaScript?
    </title>
</head>
 
<body>
    <h1 style="color: green">
        w3wiki
    </h1>
     
    <b>
        How to modify URL without reloading
        the page using JavaScript?
    </b>
     
    <p>
        Click on the button below to modify
        the current history state
    </p>
     
    <button onclick="modifyState()">
        Modify history state
    </button>
     
    <script>
        function modifyState() {
            let stateObj = { id: "100" };
            window.history.replaceState(stateObj,
                        "Page 3", "/page3.html");
        }
    </script>
</body>
 
</html>


Output:

How to modify URL without reloading the page using JavaScript ?

In this article, we are going to see how to modify URL without reloading the page using JavaScript

Below are the methods to modify the URL without reloading the page using JavaScript:

Table of Content

  • Replacing the current state with replaceState() Method
  • Adding a new state with pushState() Method

Similar Reads

Method 1: Replacing the current state with replaceState() Method

The history interface of the browser manages the browser session history. It includes the page visited in the tab or frame where the current page is located. Manipulating this state can be used to change the URL of the browser without reloading the page. TheĀ replaceState()Ā method is used to modify the current history entry and replace the properties of the state with ones in the passed parameters. The parameters of this method have 3 parts, the state object which is a serializable object about the state, the title which is the title of the new state, and the URL which is the new URL of the state. The URL can be changed by passing the required URL as a string to this method. This will change the URL of the page without reloading the page....

Method 2: Adding a new state with pushState() Method

...

Contact Us