There are two common ways to redirect the browser in JavaScript. Both use window.location
but they differ in how they interact with Session History (and hence, the browser's back button). In this lesson, you'll learn how they're different and how to use each of them.
[00:00] There are two common ways to redirect in Javascript, and both use Window.location. Window.location is a read-only location object which has several properties and methods. Two of these properties will allow us to redirect the browser. One if the href property, and the other is a method called replace.
[00:19] We can simply assign Window.location.href to https:google.com, and this will redirect the browser to Google. Alternatively, we could use the replace method by calling it with https://google.com, and this will also direct the browser to Google.
[00:36] The most noticeable difference with these two methods is with how they interact with the session history, and hence the browser back button. For an example of this, we have a page which links to two pages that utilize each of these methods of redirection.
[00:52] When we click on the href link, it will show us a redirection page, and after a second we'll be redirected to egghead.io. If we click the browser back button, it will show us the redirection page. This may be acceptable for your use case, but it can also be really annoying for the user if they get into a never ending redirect cycle when they are trying to navigate back in their history.
[01:13] In contrast, when we click on the replace link, it does the same redirection, except it uses the window.location.replace API, which will replace this redirection page in the browser's history. So, if we click the back button, it takes us back to our redirection in Javascript page, rather than the page that performed the redirection.
[01:33] To recap, let's look again at how this is accomplished in this example. We have our index.html, which links to a href.html and a replace.html page. If we look at the href.html page, there's a script that has a settimeout, with a callback that sets Window.location.href to https://egghead.io. The replace.html does the same thing, except with Window.location.replace.
[02:04] That's how you redirect a user in Javascript. If you want the redirect page in the browser's history, use Window.location.href. If you don't, then use Window.location.replace.