Skip to content

Instantly share code, notes, and snippets.

@bradoyler
Last active April 14, 2020 19:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradoyler/a02a2f3ec3fbeb2b32ccabb80b782304 to your computer and use it in GitHub Desktop.
Save bradoyler/a02a2f3ec3fbeb2b32ccabb80b782304 to your computer and use it in GitHub Desktop.
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