Redirecting to a different webpage using JavaScript ↪️ ✅

👏 THANKS: I appreciate the claps readers give because it takes me some time to write these free articles.

It’s one of the simple things that’s always hard to remember. There are 2 main ways to redirect in JavaScript (apart from HTML link tags):

Note: The difference is #2 doesn’t let you click the back button after redirect.

1.) Use window.location.href to redirect (prefer)💻

window.location.href does a redirect by simulating a mouse click to a different page. Use it like the following just by replacing the URL:

window.location.href = "https://carmont.io";

2.) or Use window.location.replace() 🌳

window.location.replace() does a HTTP redirect to go to a different page. Use it like the following just by replacing the URL:

window.location.replace("https://carmont.io");

NOTE: This option will stop users being able to go to the page before using the back button. It does this because it replace the whole document content. This is often useful in things such a payment flows where you don’t want to let the user go back.

Thanks for reading! Please leave a clap like my other readers if this helped 😊

--

--

26K+ Reads ✍🏼 Co-founder & CTO @Connect Earth. Ex-Amazon 👨‍💻 Passionate about sustainability and software👌 Views are all my own.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nicolas Carmont

26K+ Reads ✍🏼 Co-founder & CTO @Connect Earth. Ex-Amazon 👨‍💻 Passionate about sustainability and software👌 Views are all my own.