Forked from Intrepidd/turbo_frame_history_controller.ts
Last active
September 16, 2021 13:30
-
-
Save Kukunin/5033345db6da9d2edc002dc3f39702ac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Controller } from 'stimulus' | |
import { useMutation } from 'stimulus-use' | |
export default class extends Controller { | |
connect () { | |
useMutation(this, { attributes: true }) | |
this.popStateListener = this.popStateListener.bind(this) | |
window.addEventListener("popstate", this.popStateListener) | |
// Make Turbo ignore popstate events for the initial state | |
history.replaceState(this.historyState(), "", window.location.href) | |
} | |
disconnect() { | |
window.removeEventListener("popstate", this.popStateListener) | |
} | |
mutate (entries) { | |
entries.forEach((mutation) => { | |
if (mutation.type === 'attributes' && mutation.attributeName === 'src') { | |
const src = this.element.getAttribute('src') | |
if (src != null && src !== window.location.href) { | |
history.pushState(this.historyState(), "", src) | |
} | |
} | |
}) | |
} | |
popStateListener(event) { | |
if (event.state.turbo_frame_history && event.state.turbo_frame === this.element.id) { | |
this.element.src = window.location.href | |
} | |
} | |
historyState() { | |
return { | |
turbo_frame_history: true, | |
turbo_frame: this.element.id, | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This controller uses custom History tracking to make Back button work