Redirect to Another Page using JavaScript

2019-12-02 Moduatejavascript

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:

window.location.assign("https://moduate.com")

or alternatively, you can type:

window.location.href = "https://moduate.com"

Both achieve the same results.

location.href

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.assign or 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.

location.href

Remember that this method of redirection simulates a Link click.

Using location.replace

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:

window.location.replace("https://moduate.com")

location.href

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.

location.href

Remember that this method simulates an HTTP redirect.

Conclusion

There are two methods for redirecting a user to another page using only vanilla JavaScript. The first location.href or 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.