Friday, September 5, 2025
HomeLanguagesJavascriptHow can a page be forced to load another page in JavaScript...

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

In this article, we will see how can a page be forced to load another page in JavaScript.

Approach: We can use window.location property inside the script tag to forcefully load another page in Javascript. It is a reference to a Location object that is it represents the current location of the document. We can change the URL of a window by accessing it.

Syntax:

<script>
    window.location = <Path / URL>
</script>

Example:

<script>
    window.location = "https://www.geeksforgeeks.org/"
</script>

So in the above example, we see that by changing the window.location Object inside Javascript we can change the URL of our window and thus successfully load any page forcibly from our Javascript without any href tag. We will build a small working sample to learn it practically. 

Below is the step by step implementation:

Step 1: Create a file named index.html. Add a heading and two buttons to it. One button forcefully loads a page with a live URL and the other button loads a local HTML page. In the <script> tag we have two functions, one loads gfg home page, and the second loads a local HTML page using window.location property.

index.html




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
        content="IE=edge">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
</head>
  
<body>
    <h3>This is the original page</h3>
    <br>
  
    <button onclick="force_load_gfg()">
        Force Load GFG Page
    </button>
    <br><br>
  
    <button onclick="force_load_local()"> 
        Force Load Local HTML page
    </button>
  
    <script>
        function force_load_gfg() {
            window.location = 
                "https://www.geeksforgeeks.org/"
        }
  
        function force_load_local() {
            window.location = 
                "F:/gfg/PageRedirect/newPage.html"
        }
    </script>
</body>
  
</html>


Step 2: Create a file named newPage.html. This is the local HTML page that would be loaded by Javascript.

newPage.html




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" 
        content="IE=edge">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
    <title> New Page </title>
</head>
  
<body>
    <h3>This is the new loaded page</h3>
</body>
  
</html>


Output:

Output Screencast

RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6638 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11866 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7027 POSTS0 COMMENTS
Thapelo Manthata
6704 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS