In this post we will show you two methods of redirecting a user to another page using vanilla JS. The first approach has similar behaviour to a Link click, with the second approach having similar behaviour to an HTTP redirect.
The first thing we will do is open up our browser. We will be using Google Chrome in this tutorial but feel free to use Firefox if that’s your browser of choice.
Using location.href or location.assign
Once your browser has loaded, press
F12 (Windows/Linux) or
fn + F12 (macOS), on your keyboard to open up your browsers developer tools.
Make sure that the Console tab is selected.
We will be using moduate.com for demonstration purposes only. If your browser tab is already on moduate.com, please navigate away to another page before continuing with this tutorial.
Type the following into your developer tools console:
or alternatively, you can type:
window.location.href = "https://moduate.com"
Both achieve the same results.
It’s useful to note that we do not need to include window in the above commands, as it’s the global object in our browser. Just specifying
js-location.href would return the same result, but for completeness sake, we have explicitly included the window object.
Now hit enter, and notice that we are redirected to the moduate.com home page.
It’s important to note hat we can navigate back to the previous page, as the browsers sessions history has been preserved. This is the key difference between using assign or href vs the replace method discussed below.
Remember that this method of redirection simulates a Link click.
If you haven’t already done so, navigate back to the previous screen and remove the location.href line of code.
Enter the following command in the console tab:
Hit enter and you will be redirected to the moduate.com homepage. This method has similar behaviour to the previous command, however, notice that we can not go back to view the previous page. This is because the url of the original page was replaced by the url of the new page (moduate.com) in our browser pages session history.
Remember that this method simulates an HTTP redirect.
location.assign preserves your browser pages session history, appending the new url to the end of it. Where as the second
location.replace replaces the url of the current document in session history with the new url.