How to Display Changed Browser URL Without Reloading Through alert using JavaScript ?

To change the URL in the browser without loading the new page, we can use history.pushState() method and replaceState() method from JavaScript. To display the browser-URL before changing the URL we will use window.location.href in the alert() function and will use again after changing the browsers-URL.

Note: The history.pushState() method combines HTML 5 History and JavaScript pushState() method.

Syntax:

alert(" Message:" + window.location.hrf);

Below examples illustrate the above approach:

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <script type="text/javascript">
        function geeks() {
            alert("The current URL of this"
            + " page is: " + window.location.href);
        }
  
        function change_url() {
            window.history.pushState("stateObj",
                 "new page", "changedURL.html");
              
            alert("The URL of this page is: "
                    + window.location.href);
        }
    </script>
</head>
  
<body onload="geeks()">
    <a href="javascript:change_url()">
        Click to change url
    </a>
</body>
  
</html>

chevron_right


Output:

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <script type="text/javascript">
        function geeks() {
            alert("The current URL of this "
            + "page is: " + window.location.href);
        }
  
        function change_url() {
            window.history.replaceState("stateObj",
                    "new page", "changedURL.html");
              
            alert("The URL of this page is: "
                    + window.location.href);
        }
    </script>
</head>
  
<body onload="geeks()">
    <a href="javascript:change_url()">
        Click to change url
    </a>
</body>
  
</html>

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.