How do you redirect to a new page in JavaScript?
TL;DR
To redirect to a new page in JavaScript, you can use the window.location
object. The most common methods are window.location.href
and window.location.replace()
. For example:
How do you redirect to a new page in JavaScript?
Using window.location.href
The window.location.href
property is used to get or set the URL of the current page. When you set this property, the browser will navigate to the new URL, and it will create a new entry in the browser's history.
Using window.location.replace()
The window.location.replace()
method is similar to window.location.href
, but it does not create a new entry in the browser's history. This means that the user cannot use the back button to return to the original page.
Using window.location.assign()
The window.location.assign()
method works similarly to window.location.href
and creates a new entry in the browser's history.
Using window.location.reload()
If you want to reload the current page, you can use the window.location.reload()
method. This method can be useful if you want to refresh the page without changing the URL.
Using window.history.pushState()
For more advanced use cases, such as single-page applications (SPAs), you can use the window.history.pushState()
method. This method allows you to change the URL without reloading the page.