Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix back-button history for turbo-frames #103

Merged
merged 1 commit into from
Feb 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions app/javascript/controllers/turbo_frame_history_controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {

connect() {
document.addEventListener('turbo:before-fetch-request', this.beforeFetchRequest)
window.addEventListener("popstate", this.popState)
}

disconnect() {
document.removeEventListener('turbo:before-fetch-request', this.beforeFetchRequest)
window.removeEventListener("popstate", this.popState)
}

beforeFetchRequest(event) {
// Solution from: https://github.com/hotwired/turbo/issues/792
// When we do a fetch request that targets a turbo-frame, we manually update the URL by
// adding to pushState. When we do, we set a special param (refresh_on_back = true). We
// then monitor popState event, which fires every time the back button is pressed. In those
// cases we do a new Turbo visit to manually refresh the page.
//
// This "fixes" history state for turbo frames, but it doesn't use the Turbo page cache.
// This simply means that going back will cuase a new server request, but that's okay for our
// purposes.
let fetchTargetingFrame = (event.detail.fetchOptions.headers['Turbo-Frame'] != undefined)

if (fetchTargetingFrame) {
Turbo.cache.exemptPageFromPreview()
history.replaceState({page: document.title, refresh_on_back: true}, '', window.location.pathname);
history.pushState({page: 'new title', refresh_on_back: true}, '', event.detail.url.pathname) // not sure how to get page title
}
}

popState(event) {
if (event.state && event.state.refresh_on_back) {
Turbo.visit(window.location.href, { action: "replace" })
}
}
}
2 changes: 1 addition & 1 deletion app/views/shared/_two_columns.html.erb
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<%= turbo_stream_from @conversation %>

<div class="flex h-screen"
data-controller="click-toggle"
data-controller="click-toggle turbo-frame-history"
data-click-toggle-flippable-class="!hidden"
>

Expand Down
Loading