Languages
[Edit]
EN

JavaScript - how to redirect to another web page?

8 points
Created by:
GamerGoals22
364

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

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

For more details look at the 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>
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join