Skip to content

Instantly share code, notes, and snippets.

@fabrizim
Last active April 12, 2024 14:33
Show Gist options
  • Save fabrizim/52066b4a70a919f9c508 to your computer and use it in GitHub Desktop.
Save fabrizim/52066b4a70a919f9c508 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);
}
})();
@phil2phil
Copy link

it does not shrink

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