Skip to content
Related Articles

Related Articles

How to redirect to another webpage using JavaScript ?

View Discussion
Improve Article
Save Article
  • Last Updated : 17 Nov, 2021
View Discussion
Improve Article
Save Article

In this article, we will know how to redirect the webpage to another using Javascript, along with understanding its implementation through the examples.

There are several methods to redirect to another webpage using JavaScript. Some of them are listed below:

Syntax:

location.href="URL"
      or
location.replace("URL")
      or
location.assign("URL")

Parameters: It accepts a single parameter URL which is required. It is used to specify the reference of the new webpage.

Return Value: No return value.

Example 1: This example illustrates the use of the location.href property.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <h2>Welcome to GeeksforGeeks</h2>
    <p>This is the example of <i>location.href</i> way. </p>
  
    <button onclick="myFunc()">Click me</button>
      
    <!--script to redirect to another webpage-->
    <script>
    function myFunc() {
        window.location.href = "https://www.geeksforgeeks.org/";
    }
    </script>
</body>
  
</html>

Output: 

location.href Property

Example 2: This is an example of a location.replace() method.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <h2>Welcome to GeeksforGeeks</h2>
    <p>This is the example of <i>location.replace</i> method. </p>
  
    <button onclick="myFunc()">Click me</button>
      
    <!--script to redirect to another webpage-->
    <script>
    function myFunc() {
        location.replace("https://www.geeksforgeeks.org/");
    }
    </script>
</body>
  
</html>

Output:

location.replace

Example 3: This example uses the location.assign() method.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Location assign() Method</title>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
    <h2>Location assign() Method</h2>
    <button onclick="load()">Click Here!</button>
      
    <!-- Script to use Location assign() Method -->
    <script>
    function load() {
        location.assign("https://ide.geeksforgeeks.org/index.php");
    }
    </script>
</body>
  
</html>

Output:

location.assign

NOTE: The output of all the methods will be the same but the location.replace() method removes the URL of the current document from the document history. Thus, it is good to use location.assign() method if you want the option to navigate back to the original document. 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!