Manage browser history manually for one part of my Turbolinks-enabled Rails 5 app

Viewed 1047

I am using Turbolinks but I would like to take over history management for one piece of my application's flow. Specifically:

  1. User loads product page
  2. User clicks on product and product modal appears (without reloading the page)
  3. Upon loading the product model the URL updates to the loaded product's URL
  4. User clicks "back"
  5. The model disappears and the user returns to the product page but the product page doesn't reload

If I manually history.pushState(null, null, PRODUCT_URL) after the user clicks in step (2) then everything works except step (5) during which Turbolinks reloads the entire product page.

Ideally I could hook into the window's popstate event and cancel Turbolink's ajax request, but per Turbolinks docs "Restoration visits cannot be canceled and do not fire turbolinks:before-visit"

1 Answers

When pushing to the history, Turbolinks adds its own data to the state (i.e. the first argument to history.pushState. It then uses this data on the popstate event, to restore the page.

To manually push to the history in the format the Turbolinks understands, rather than calling history.pushState directly, you might have some success using the following in step 2:

Turbolinks
  .controller
  .pushHistoryWithLocationAndRestorationIdentifier(PRODUCT_URL, Turbolinks.uuid())

It's worth noting that whilst this is a public method, it's not documented, and therefore maybe removed in future versions. However, given that Turbolinks is rather stable, it should be reasonably safe to use.

Hope that helps.

Related