Last active
March 12, 2021 00:55
-
-
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.
This file contains hidden or 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' | |
// 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