Skip to content

Instantly share code, notes, and snippets.

@rakeden
Forked from fabrizim/iframe.js
Created April 12, 2024 14:33
Show Gist options
  • Save rakeden/f4f5e66e18971b960ec6cdf3f1fbb1d8 to your computer and use it in GitHub Desktop.
Save rakeden/f4f5e66e18971b960ec6cdf3f1fbb1d8 to your computer and use it in GitHub Desktop.
Javascript for updating iframe height with postMessage
(function(){
function post_height(){
var msg = JSON.stringify({event:'size', height: document.body.scrollHeight});
window.top.postMessage(msg, '*');
}
var onload = window.onload;
window.onload = function(){
if( onload && typeof onload =='function'){
onload();
}
post_height();
setInterval(post_height, 1000);
window.top.postMessage(JSON.stringify({event:'load'}), '*');
};
})();
(function(){
function receiveMessage(e){
var iframes = document.getElementsByTagName('iframe');
for(var i=0; i<iframes.length; i++){
var iframe = iframes[i];
var src = iframe.src;
if( src && src.indexOf( e.origin ) === 0 ){
var data = JSON.parse(e.data);
switch( data.event ){
case 'size':
iframe.style.height = (data.height+10)+'px';
break;
}
}
}
}
if( window.addEventListener ){
window.addEventListener('message', receiveMessage, false);
}
else {
window.attachEvent('onmessage', receiveMessage);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment