Skip to content

Instantly share code, notes, and snippets.

@ourmaninamsterdam
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ourmaninamsterdam/bbb53e02016f61f45341 to your computer and use it in GitHub Desktop.
Save ourmaninamsterdam/bbb53e02016f61f45341 to your computer and use it in GitHub Desktop.
Iframe Resizer (no dependencies) with AMD/global definitions
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define('iframeResizer', function (iframeResizer) {
return (root.iframeResizer = factory());
});
} else {
root.iframeResizer = factory();
}
}(this, function () {
return function(msgPrefix, targetOrigin, minFrameHeight,) {
var timer, frameDefaultOverflow;
minFrameHeight = minFrameHeight || 250;
targetOrigin = targetOrigin || '*';
return {
start : function() {
if(!window.postMessage) return;
var currentHeight = 0,
bodyNode = document.body,
frameTopMargin,
frameBtmMargin;
frameDefaultOverflow = window.getComputedStyle(bodyNode).overflow;
document.documentElement.style.overflow = 'hidden';
frameTopMargin = parseInt(window.getComputedStyle(bodyNode).marginTop, 16);;
frameBtmMargin = parseInt(window.getComputedStyle(bodyNode).marginBottom, 16)
timer = setInterval(function() {
var documentHeight = Math.max(
frameTopMargin + frameBtmMargin + bodyNode.clientHeight,
minFrameHeight
);
if(documentHeight !== currentHeight) {
window.parent.postMessage(msgPrefix + documentHeight, targetOrigin);
currentHeight = documentHeight;
}
}, 200);
},
stop: function() {
clearInterval(timer);
document.documentElement.style.overflow = frameDefaultOverflow;
}
}
}
}));
@ourmaninamsterdam
Copy link
Author

// Initialise
var iframer = iframeResizer('resize', 'http://www.foo.com', 250);

// Start
iframer.start();

// Stop
iframer.stop();
// Using AMD
var iframer = require('iframeResizer')('resize', 'http://www.foo.com', 250);

// Start
iframer.start();

// Receiving messages
window.addEventListener('message', function(event){
   if(event.origin !== 'http://www.foo.com') return;
  // Note: if you included a msgPrefix then you will need to filter this from event.data before applying this    
  document.querySelector('iframe').style.height = event.data + 'px';  
});

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