Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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.

HTML




<!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

  • The assign function is similar to the href property as it is also used to navigate to a new URL.
  • The assign method, however, does not show the current location, it is only used to go to a new location.
  • Unlike the replace method, the assign method adds a new record to history (so that when the user clicks the “Back” button, he/she can return to the current page).

Syntax:

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

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

HTML




<!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:



Last Updated : 30 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads