Last active
March 17, 2020 15:25
-
-
Save manufitoussi/7529fa882ff0b737f257 to your computer and use it in GitHub Desktop.
Synchronisation between iframe hash and hosting window hash. Usefull with an Ember application with routes hosted in an iframe
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
<!DOCTYPE html> | |
<html lang="fr-fr"> | |
<head> | |
<meta charset="utf-8"> | |
<title>Ember App in an iframe</title> | |
<style> | |
body { | |
padding:0; | |
margin:0; | |
} | |
.iframe-container { | |
position:fixed; | |
top:75px; | |
bottom:0; | |
right:0; | |
left:0; | |
} | |
#EmberApp { | |
width: 100%; | |
height: 100%; | |
border:1px solid rgb(255,80,80); | |
} | |
</style> | |
</head> | |
<body> | |
<h3>Ember App in an iframe</h3> | |
<div class="iframe-container"> | |
<iframe id="EmberApp" src="ember-app.html"></iframe> | |
</div> | |
<script type="text/javascript"> | |
var iframe = document.querySelector('iframe#EmberApp'); | |
var updateIframeSrcFromLocation = function () { | |
if(iframe.contentWindow.location.hash === window.location.hash) { | |
return; | |
} | |
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); | |
} | |
}; | |
var updateLocationFromIframeSrc = function () { | |
if(iframe.contentWindow.location.hash === window.location.hash) { | |
return; | |
} | |
window.location.hash = iframe.contentWindow.location.hash; | |
}; | |
window.addEventListener("hashchange", updateIframeSrcFromLocation); | |
iframe.contentWindow.addEventListener("hashchange", updateLocationFromIframeSrc); | |
updateIframeSrcFromLocation(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment