How to not break the back button in JavaScript heavy work

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the web-development category.

Last Updated: 2024-04-18

After building the tax calculator single page web-app, we pushed it live. I went home and showed it to my girlfriend. She tested it with the figures of her salary and got a tax result of X. Then she wanted to tweak a value so hit back. Unfortunately this took her to the homepage - and she lost all the form input.

Since there is no "back button event" for JavaScript to latch onto, we need to do things a bit manually. One trick is to relocate to the same URL using JavaScript but with a different hash fragment.

Also you need to hook into the popstate callback

window.location.hash = "#calculator_results";
window.addEventListener("popstate", Calculators.prepareForRecalculation)

Now, calling history.back() (in JavaScript or with the browser back button) will execute the last item in popstate - the function Calculators.prepareForRecalculation

Resources