Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62
Subscribe to my email list now at http://jauyeung.net/subscribe/
Redirecting to another webpage is a common operation we do in JavaScript programs.
In this article, we’ll look at how to redirect to a given URL with JavaScript.
window.location.replace
One way to redirect to a given URL is to use the window.location.replace
method.
For instance, we can write:
window.location.replace('https://yahoo.com')
We just pass in the URL in there.
replace
doesn’t keep a record in the session history.
We can omit window
since window
is the global object:
location.replace('https://yahoo.com')
window.location.href
We can also set the window.location.href
property to the URL we want to go to.
For instance, we can write:
window.location.href = 'https://yahoo.com'
Setting window.location.href
adds a record to the browser history, which is the same as clicking on a link.
Also, we can shorten this to location.href
since window
is global:
location.href = 'https://yahoo.com'
window.location.assign
Also, we can call window.location.assign
to navigate to the URL we want.
For instance, we can write:
window.location.assign('https://yahoo.com')
To navigate to ‘https://yahoo.com'
.
It also keeps a record in the browser history.
We can shorten this to location.assign
since window
is the global object:
location.assign('https://yahoo.com')
Conclusion
There are a few ways to navigate to a URL in our JavaScript app.
Top comments (0)