Skip to content

Instantly share code, notes, and snippets.

@bradoyler
Last active Apr 14, 2020
Embed
What would you like to do?
adaptive iframe using postMessage()
<h2> Hello World! </h2>
<script>
function iframeResize() {
var body = document.body, html = document.documentElement;
var height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
var location = document.location.href;
window.parent.postMessage(["setHeight", height, location], "*");
}
iframeResize();
$(window).resize(iframeResize);
</script>
<iframe id="iframe1" src="child.html" frameborder="0" width="100%" scrolling="no" height="0"></iframe>
<script>
window.addEventListener('message', function(e) {
var $iframe = document.getElementById('iframe1');
var height = e.data[1];
if (e.data[0]==='setHeight') {
$iframe.style.height = height + 'px';
}
}, false);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment