Languages
[Edit]
EN

JavaScript - how to redirect to another web page?

8 points
Created by:
AnnLen
9180

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>

 

Native Advertising
50 000 ad impressions - 449$
ūüöÄ
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

‚̧ԳŹūüíĽ ūüôā

Join