How to redirect to another page using JavaScript

Published on

There's a quite a few different ways to achieve this in JavaScript. To simulate similar behaviour to clicking on a link we can simply use:

window.location.href = 'https://blog.fraserhamilton.dev/';

This will redirect the user and create a new entry in your browsers history stack, meaning you can go back to the previous page using the back button. If you wish to instead simulate a http redirect we can use replace:

window.location.replace('https://blog.fraserhamilton.dev/');

We can also use the window.history methods to navigate across the browsers history stack:

window.history.forward();
window.history.back();

window.history.go(1);
// equivalent to window.history.forward()

window.history.go(-2);
// equivalent to calling window.history.back() twice