How to redirect to another webpage in JavaScript
In this tutorial, we are going to learn about how to redirect a user from one page to another page in JavaScript.
Consider we have contact form whenever a user submits a form we need to redirect the user from
/contact-page
to /home-page
or some other page. In such cases, we can use the href
property or replace()
method in JavaScript.
Using href
window.location.href = "https://google.com"
Just open your console and run the above code, you will be redirected from the current page to google.com
.
Using replace() method
window.location.replace("https://google.com")
The difference between replace()
and href
is, the replace()
method doesn’t save the current page in the session history, so that, we can’t use the browser back button to navigate back to the previous page.
Redirecting from one page to another page by using a button click
Example:
Html
<button class="btn" >Click</button>
JavaScript
const btn = document.querySelector('.btn')
btn.addEventListener('click',()=>{
window.location.href = "https://yournewurl.com"
})