Better event handling, fix race condition, make history work

This commit is contained in:
Michael Wyraz 2021-11-03 21:14:45 +01:00
parent 4be1964c56
commit 860c9bbe1d
1 changed files with 20 additions and 9 deletions

View File

@ -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;
}) ();