Skip to content
Related Articles

Related Articles

How to redirect to another webpage using JavaScript?
  • Last Updated : 24 Apr, 2019

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 single parameter URL which is required. It is used to specify the reference of new webpage.

Return Value: No return value.

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




    <!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.wikipedia.org/";
             }
          </script>
       </body>
    </html>

    Output:
    Before clicking click me button:

    After clicking click me button: The Wikipedia page will be opened.

  • Example 2: This is the example of location.replace() method.




    <!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.wikipedia.org/");
             }
          </script>
       </body>
    </html>

    Output:
    Before clicking click me button:

    After clicking click me button: The Wikipedia page will be opened.

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




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

    • Before Clicking the button:
    • After Clicking the button:

NOTE: The output of all the methods will be same but location.replace() method removes the URL of 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.

Supported Browsers: Given below the list of browser support for the above methods:-

  • Google Chrome
  • Apple Safari
  • Firefox
  • Opera
  • Edge



My Personal Notes arrow_drop_up
Recommended Articles
Page :