Ben Borgers

How to go back one page and refresh with JavaScript

September 30, 2020

Let's say you want to have a link that sends the user back one page, but also refreshes the page so that last page's content isn't stale.

Here's a way you can do it:

// On button press, or something else:
document.referrer ? window.location = document.referrer : history.back()

This looks to see if we have a referrer, which is the last page that the user came from before this page. If there is, we navigate to that page.

If there isn't, we fall back to using history.back() as an alternative, which sends the user back without refreshing.

More blog posts

Subscribe to my newsletter for a monthly round-up of new blog posts and projects Iā€™m working on!

Twitter ↗ RSS feed ↗