How to resize an iframe from within the iframe - using postMessage for communication

9 comments

In the containing page put the following code:


	$(document).ready(function() {
		// Create IE + others compatible event handler
		var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
		var eventer = window[eventMethod];
		var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

		// Listen to message from child window
		eventer(messageEvent, function(e) {
			if (e.data.indexOf("setheight:") > -1) {
				var height = e.data.split(":")[1];
				$("#iframe").css("height", height + "px");
			}
		}, false);
		
	});

In the iframe put this code:

$(document).ready(function() {
	if (parent.postMessage) {
		var oldHeight = 0;

		var resizer = function () {
			var height = $("html").height();
			if (height != oldHeight) {
				parent.postMessage("setheight:" + height, "*");
			}
		};

		window.setInterval(resizer, 200);
	}
});

Comments


Leave a Comment