Open In App

How can a page be forced to load another page in JavaScript ?

In JavaScript, you can force a page to load another page by using the window.location object. There are a few methods to achieve this. To force a page to load another page in JavaScript, we have multiple approaches:

Below are the approaches used to force a page to load another page in JavaScript:



Approach 1: Using window.location.replace

The replace function is used to navigate to a new URL without adding a new record to the history.



Syntax:

// Redirect to another page using replace
window.location.replace('https://www.example.com');

Example: This example shows the use of the window.location.replace which is used to load another page in JavaScript.




<!DOCTYPE html>
<html>
<body>
    <button onclick="replaceLocation()">
        Replace current webpage
    </button>
    <script>
        function replaceLocation() {
 
            // Replace the current location
            // with new location
            let newloc = "https://www.geeksforgeeks.org/";
            window.location.replace(newloc);
        }
    </script>
</body>
</html>

Output:

Approach 2: Using window.location.assign Property

Syntax:

window.location.assign("https://geeksforgeeks.org/")

Example: This example shows the use of the window.location.assign property.




<!DOCTYPE html>
<html>
<body>
    <button onclick="assignLocation()">
        Go to new webpage
    </button>
     
    <script>
        function assignLocation() {
 
            // Go to another webpage (geeksforgeeks)
            let newloc = "https://www.geeksforgeeks.org/";
            window.location.assign(newloc);
        }
    </script>
</body>
</html>

Output:


Article Tags :