Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mathiasmadsen/2e6e8c904e345a089d1d99532e016f38 to your computer and use it in GitHub Desktop.
Save mathiasmadsen/2e6e8c904e345a089d1d99532e016f38 to your computer and use it in GitHub Desktop.
# Parent code
<iframe
id="iframe"
src="child.html"
allowtransparency="true"
width="100%"
type="text/html"
frameborder="0"
style="width: 100%; border: none"
></iframe>
<script nomodule>
// IE
window.onmessage = function (e) {
if (e.data.hasOwnProperty('frameHeight')) {
document.getElementById('iframe').style.height =
e.data.frameHeight + 50 + 'px';
}
};
</script>
<!--[if !IE]>-->
<script>
window.onmessage = (e) => {
if (e.data.hasOwnProperty('frameHeight')) {
document.getElementById('iframe').style.height = `${
e.data.frameHeight + 30
}px`;
}
};
</script>
<!--<![endif]-->
# Child (iframe)
<script nomodule>
// IE
let height;
function sendPostMessage() {
if (height !== document.body.offsetHeight) {
height = document.body.offsetHeight;
window.parent.postMessage(
{
frameHeight: height,
},
'*'
);
console.log(height); // check the message is being sent correctly
}
}
setTimeout(function () {
window.onload = sendPostMessage();
window.onresize = sendPostMessage();
}, 200);
</script>
<!--[if !IE]>-->
<script>
let height;
const sendPostMessage = () => {
if (height !== document.body.offsetHeight) {
height = document.body.offsetHeight;
window.parent.postMessage(
{
frameHeight: height,
},
'*'
);
console.log(height); // check the message is being sent correctly
}
};
window.onload = () => sendPostMessage();
window.onresize = () => sendPostMessage();
</script>
<!--<![endif]-->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment