Skip to content

Redirect in JavaScript

  • by

In JavaScript, you can use the window.location object to perform a redirect to a different URL. There are a few different ways to accomplish this, depending on your specific requirements.

1. Redirect to a new URL:

Using window.location.href:

window.location.href = "https://www.example.com";

Using window.location.replace():

window.location.replace("https://www.example.com");

2. Redirect to the previous page in the browser history:

window.history.back();

3. Redirect to a specific page in the browser history (forward):

window.history.forward();

4. Redirect to a new URL after a delay (in milliseconds):

setTimeout(function() {
  window.location.href = "https://www.example.com";
}, 3000); // Redirect after 3 seconds

5. Redirect to a new URL in a new browser tab or window:

window.open("https://www.example.com", "_blank");

Make sure to handle any necessary cleanup or data saving before initiating a redirect.

Redirect in JavaScript example

Simple example code.

<!DOCTYPE html>
<html>
  <head>
    <title>Redirect Example</title>
    <script>
      // Redirect using window.location.href
      function redirectToExample() {
        window.location.href = "https://www.example.com";
      }

      // Redirect using window.location.replace()
      function redirectToGoogle() {
        window.location.replace("https://www.google.com");
      }
    </script>
  </head>
  <body>
    <button onclick="redirectToExample()">Go to Example.com</button>
    <button onclick="redirectToGoogle()">Go to Google.com</button>
  </body>
</html>

Output:

Redirect in JavaScript

How to Redirect to Another Webpage?

Answer: To redirect to another webpage using JavaScript, you can utilize the window.location object. Here’s an example of how to implement a redirect:

<!DOCTYPE html>
<html>
<head>
  <title>Redirect Example</title>
</head>
<body>
  <h1>Redirect Example</h1>
  <button onclick="redirectToExample()">Redirect</button>

  <script>
    function redirectToExample() {
      window.location.href = "https://www.example.com";
    }
  </script>
</body>
</html>

Comment if you have any doubts or suggestions on this Js redirect code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *