From 860c9bbe1d887cb487bdd55e4d9cf4235f84581d Mon Sep 17 00:00:00 2001 From: Michael Wyraz Date: Wed, 3 Nov 2021 21:14:45 +0100 Subject: [PATCH] Better event handling, fix race condition, make history work --- html/embed.js | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/html/embed.js b/html/embed.js index a922a14..32c5b0e 100644 --- a/html/embed.js +++ b/html/embed.js @@ -1,4 +1,5 @@ (function() { + var iframe=document.getElementById("meshviewer-embedded") if (!iframe) { console.log("IFrame 'meshviewer-embedded' not found") @@ -8,17 +9,27 @@ console.log("Element 'meshviewer-embedded' seems not to be a valid iframe") return; } - if (document.location.hash) { - window.setTimeout(function() { - iframe.contentWindow.location.hash = document.location.hash; - }, 0); - } + + function updateIframeHash() { // see https://gist.github.com/manufitoussi/7529fa882ff0b737f257 + if(iframe.contentWindow.location.host !== "") { + // iframe already loaded. + iframe.contentWindow.location.hash = window.location.hash; + } else { + // iframe is just starting. + var newHash = window.location.hash; + var srcStr = iframe.getAttribute('src'); + var words = srcStr.split('#'); + var href = words[0]; + var newSrc = href + newHash; + iframe.setAttribute('src', newSrc); + } + }; + + updateIframeHash(); iframe.contentWindow.addEventListener("message", (event) => { if (event && event.data && event.data.hash) { - window.location.hash = event.data.hash; + window.location.replace(event.data.hash); } }, false); - window.onhashchange = function () { - iframe.contentWindow.location.hash = document.location.hash; - }; + window.onhashchange = updateIframeHash; }) ();