Skip to content

Instantly share code, notes, and snippets.

@bkeepers
Last active March 12, 2021 00:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bkeepers/4683e3b4fc583d083800659a84fac717 to your computer and use it in GitHub Desktop.
Save bkeepers/4683e3b4fc583d083800659a84fac717 to your computer and use it in GitHub Desktop.
Stimulus controller to save location of same-origin iframe in hash of parent window and restore on reload.
import { Controller } from 'stimulus'
// Stimulus controller to save location of same-origin iframe in hash of parent
// window and restore on reload.
//
// <iframe src="…"
// data-controller="iframe-location"
// data-action="load->iframe-location#save">
// </frame>
//
export default class extends Controller {
connect () {
this.base = this.element.src
this.restore()
window.addEventListener('hashchange', () => this.restore(), false)
}
// Save the iframe location to the current location hash
save () {
this.hashLocation = this.iframeLocation
}
// Restore the current location hash in the iframe
restore () {
this.iframeLocation = this.hashLocation
}
get hashLocation () {
return window.location.hash.slice(1)
}
set hashLocation (newLocation) {
if (this.hashLocation !== this.iframeLocation) {
window.location.hash = this.iframeLocation
}
}
// Get the current location of the iframe, excluding the original base url
get iframeLocation () {
return this.element.contentWindow.location.toString().replace(this.base, '')
}
// Update the iframe location
set iframeLocation (newLocation) {
if (newLocation && newLocation !== this.iframeLocation) {
this.element.contentWindow.location = this.base + newLocation
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment