In a Turbo/Rails (7.1) application, Turbo does not respect the anchor
value specified in the redirect_to
method with a :see_other
status. I would expect that the page automatically scrolls to the location of the anchor, however, I think due to some fetch()
issues the anchor is lost and I end up at the top of the page.
This is true for GET and PATCH (POST) requests. The scenario that isn't working is as follows:
- link_to with turbo_method of patch
- controller receives the request and then redirects with an anchor to a new page
- the redirect occurs but the anchor is lost and the page doesn't scroll
An example of where this is particularly problematic is for notifications (which we do through a PATCH) to a discussion-like post. We want the user to click a notification, have the notification mark as read and then redirect to the specific comment on a page that the notification was associated with.
In the above scenario, I expect that clicking the link, then redirect_to with an anchor would result in the user landing on a page and automatically scrolling to the element with the anchor id.
I've created a repo to further demonstrate the issue, and hope to find that others are facing the same issue and/or have found a way around it: https://github.com/harled/turbo-anchor-issue
This same topic has been raised via the Turbo GitHub issues here: https://github.com/hotwired/turbo/issues/211
I've spent a far amount of time tracing through the Turbo code with the browser debugger and my conclusion is that fetch (and opaque redirects) are the issue which means some type of app-land workaround is necessary.
Here is a workaround that functions Turbo GET/PATCH requests with redirect_to that include an anchor, something like:
The gist of it is to switch the anchor to a query parameter (which is forwarded) and then use a little bit of javascript to clean-up the URL and scroll the page.
It doesn't feel clean, but it does seem to work. It also avoids having the developers learn a new way to interact with
redirect_to
and theanchor:
parameter.The full repo is available in this branch: https://github.com/harled/turbo-anchor-issue/tree/turbo-anchors