Skip to content

Instantly share code, notes, and snippets.

@vaskozl
Created November 6, 2024 18:16
Show Gist options
  • Save vaskozl/d64517dd3b70d69428f857fa140372b8 to your computer and use it in GitHub Desktop.
Save vaskozl/d64517dd3b70d69428f857fa140372b8 to your computer and use it in GitHub Desktop.
htmz URL history support + innerHTML
<script>
function htmz(frame) {
// ----------------------------------------------------------------------
// History + innerHTML
// ----------------------------------------------------------------------
setTimeout(() => {
const el = document .querySelector(frame.contentWindow.location.hash || null)
el.innerHTML = frame.contentDocument.body.innerHTML;
const urlWithoutFragment = new URL(frame.contentWindow.location.href);
urlWithoutFragment.hash = ""; // Remove the fragment
history.replaceState(null, "", urlWithoutFragment.href);
});
}
</script>
<iframe hidden="" name="htmz" onload="window.htmz(this)"></iframe>
<a href="flower.html#my-element" target=htmz>Flower</a>
<a href="rock.html#my-element" target=htmz>Rock</a>
<div id="my-element"></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment