How to Redirect a Web Page with JavaScript

To redirect a URL page with JavaScript you need to set the window.location object. There are several ways to change the location property on the window object:

  • window.location.href - returns the URL of the current page.
<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <script>
      let url = "https://www.w3docs.com";
      window.location.href = url;
    </script>
  </body>
</html>
  • window.location.hostname - returns the name of the Internet host of the current page.
<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <button type="button" onclick="redirectFunc()">Click and go to the page</button>
    <script>
      function redirectFunc() {
        window.location.href = "https://www.w3docs.com/";
      }
    </script>
  </body>
</html>
  • window.location.replace - removes current URL from the history and replaces it with a new URL which disables to go to the previous page using the back button.
<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <script>
      function redirectFunc() {
        window.location.replace("https://www.w3docs.com/");
      }
      setTimeout("redirectFunc()", 2000);
    </script>
  </body>
</html>
  • window.location.assign - keeps the history and makes it possible to go back to the original page just clicking on the back button.
<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <script>
      function redirectFunc() {
        window.location.assign("https://www.w3docs.com/");
      }
      setTimeout("redirectFunc()", 2000);
    </script>
  </body>
</html>

You had better use window.location.replace instead of .href because the replace method navigates to the URL without adding a new record to the history; thus the reader won’t be lost in an endless back-button mess.

Use .href if you want to make the user click on a link, and use .replace if you're going to make an HTTP redirect.
If JavaScript is disabled in the browser, this will not work.

Learn how to redirect web pages with HTML, PHP , Apache and Node.js .


Do you find this helpful?

Related articles