Skip to content

Instantly share code, notes, and snippets.

@lajlev
Created May 27, 2013 12:16
Show Gist options
  • Save lajlev/5656770 to your computer and use it in GitHub Desktop.
Save lajlev/5656770 to your computer and use it in GitHub Desktop.
Using postMessage to set iframe height dynamicly. Based on http://stackoverflow.com/questions/5606920/cross-domain-iframe-resizer/6940531#6940531
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page</title>
<style>
body {
background: pink;
}
iframe {
border: none;
width: 100%;
}
</style>
</head>
<body>
<script type="text/javascript">
function resizeCrossDomainIframe(id, other_domain) {
var iframe = document.getElementById(id);
window.addEventListener('message', function(event) {
if (event.origin !== other_domain) return; // only accept messages from the specified domain
if (isNaN(event.data)) return; // only accept something which can be parsed as a number
var height = parseInt(event.data) + 32; // add some extra height to avoid scrollbar
iframe.height = height + "px";
}, false);
}
</script>
<iframe src='http://lajlev.dk/downloads/widget.html' id="my_iframe" onload="resizeCrossDomainIframe('my_iframe', 'http://lajlev.dk');">
</iframe>
</body>
</html>
<!DOCTYPE html>
<head>
<style>
body {
background: red;
}
img {
max-width: 100%;
}
</style>
</head>
<body onload="parent.postMessage(document.body.scrollHeight, 'http://laj.lv/test');">
<h3>Got post?</h3>
<p>Lots of stuff here which will be inside the iframe.</p>
<img src="http://placekitten.com/300/300" alt="">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis, voluptate, assumenda, unde aliquid suscipit maiores porro at iusto et deleniti facere cum quo quis consequuntur nihil ex laboriosam minus ratione.</p>
</body>
</html>
@jadamec
Copy link

jadamec commented Dec 20, 2019

You saved my hours!! Thanks a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment