Hotwire Discussion

Back button not working

Hello,

I have a page with a URL of /cars. I have some onpage live filters on this page and this uses the following to update the page URL:

history.pushState({}, '', config.url)

This updates the URL correctly to something like /cars?make=12.

If I then click on a resulting filtered car I get a new page with a URL like /cars/34 and the issue I have is that when I click the Back button in my browser, the browser shows the previous URL but the page doesn’t change.

Any ideas how I can fix this?

Thanks,
Neil

Hey,

so what you are doing is correct. you are updating the browser url successfully. So when the browser changes from /cars?make=12 to /cars/34. What you are doing is updating the browser url.

What’s important here is when you update the browser url, you also update the Turbo history. so basically you have two set of historys when using turbo.

navigator.history which is the browser url navigator.
Turbo.navigator.history which corresponds to the history stored inside the turbo engine.

To solve your issue, aside from updating the browser url manually. you also need to update the turbo history as well.

 history.pushState({}, null, newUrl);
 Turbo.navigator.history.push(newUrl);

I saw this from somewhere on here answered by someone, kudos to them.

1 Like

Fantastic! I had actually tried that second line on its own but what made the difference was having both lines at the same time.

Works perfectly.

Thanks.

1 Like