Languages
[Edit]
EN

JavaScript - how to redirect to another web page?

8 points
Created by:
AnnLen
1777

In JavaScript there is available window.location object that helps to navigate to web page directly from font-end level (web browser). location object provides few properties and methods from which most useful for making redirection are:

  • location.replace method
  • location.assign method
  • location.href property
  • based on link element (a tag with href attribute)

For more details look at below examples.

1. location.replace method example

<!doctype html>
<html>
<body>
  <script>

    location.replace('https://dirask.com/about');

  </script>
</body>
</html>

Note: this redirection removes current web page from navigation history.

Result:

JavaScript - location.replace method redirection to Dirask About web page.
JavaScript - location.replace method redirection to Dirask About web page.

2. location.assign method example

<!doctype html>
<html>
<body>
  <script>

    location.assign('https://dirask.com/about');

  </script>
</body>
</html>

Note: this redirection keeps current web page in navigation history.

 Result:

JavaScript - location.assign method redirection to Dirask About web page.
JavaScript - location.assign method redirection to Dirask About web page.

3. location.href property example

<!doctype html>
<html>
<body>
  <script>

    location.href = 'https://dirask.com/about';

  </script>
</body>
</html>

Note: this redirection keeps current web page in navigation history.

Result:

JavaScript - location.href property redirection to Dirask About web page.
JavaScript - location.href property redirection to Dirask About web page.

4. Link element example

Note: run it in separated file to see effect

<html>
<body>
  <a id="link" href="https://dirask.com"></a>
  <script>
  
    var element = document.querySelector('#link');
    element.click();
  
  </script>
</body>
</html>

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.