Skip to content

Instantly share code, notes, and snippets.

@jamenlyndon
Last active December 28, 2023 04:30
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jamenlyndon/170af98d77d93a0df01c to your computer and use it in GitHub Desktop.
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
Copy link
Author

jamenlyndon commented Jan 16, 2023 via email

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