Fraser Hamilton

How to redirect to another page using JavaScript

July 18, 2020

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)
window.history.go(-2)


Written by Fraser Hamilton a full stack developer based out of Edinburgh, Scotland.

© 2020, Fraser Hamilton