Skip to content

Instantly share code, notes, and snippets.

@jamenlyndon
Last active May 21, 2024 08:20
Show Gist options
  • Select an option

  • Save jamenlyndon/170af98d77d93a0df01c to your computer and use it in GitHub Desktop.

Select an option

Save jamenlyndon/170af98d77d93a0df01c to your computer and use it in GitHub Desktop.
Resize iframe height to fit content (works cross domain)
<script type='text/javascript' src="js/jquery.min.js"></script>
<script type='text/javascript'>
// Size the parent iFrame
function iframeResize() {
var height = $('body').outerHeight(); // IMPORTANT: If body's height is set to 100% with CSS this will not work.
parent.postMessage("resize::"+height,"*");
}
$(document).ready(function() {
// Resize iframe
setInterval(iframeResize, 1000);
});
</script>
<iframe src='example.html' id='edh-iframe'></iframe>
<script type='text/javascript'>
// Listen for messages sent from the iFrame
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
// If the message is a resize frame request
if (e.data.indexOf('resize::') != -1) {
var height = e.data.replace('resize::', '');
document.getElementById('edh-iframe').style.height = height+'px';
}
} ,false);
</script>
@jamenlyndon

jamenlyndon commented Jan 16, 2023 via email

Copy link
Copy Markdown
Author

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