EN
JavaScript - how to redirect to another web page?
8 points
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
methodlocation.assign
methodlocation.href
property- based on the link element (
a
tag withhref
attribute)
For more details look at the below examples.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<script>
5
6
location.replace('https://dirask.com/about');
7
8
</script>
9
</body>
10
</html>
Note: this redirection removes current web page from navigation history.
Result:

xxxxxxxxxx
1
2
<html>
3
<body>
4
<script>
5
6
location.assign('https://dirask.com/about');
7
8
</script>
9
</body>
10
</html>
Note: this redirection keeps current web page in navigation history.
Result:

xxxxxxxxxx
1
2
<html>
3
<body>
4
<script>
5
6
location.href = 'https://dirask.com/about';
7
8
</script>
9
</body>
10
</html>
Note: this redirection keeps current web page in navigation history.
Result:

Note: run it in separated file to see effect
xxxxxxxxxx
1
<html>
2
<body>
3
<a id="link" href="https://dirask.com"></a>
4
<script>
5
6
var element = document.querySelector('#link');
7
element.click();
8
9
</script>
10
</body>
11
</html>