I want to access the iframe my page is in and resize it. By the way I'm doing it in javascript.
It's something like parent and height or offsetHeight.
<iframe src="mypage.asp" height="400" width="400" ></iframe>
And in mypage.asp I do sth similar like this:
var h = // new height;
parent.height = h;
But it ain't all right? Somebody else who knows more?
2 Answers 2
Try this if you want to resize the iframe from within the page that is loaded in your iframe. It seems to work locally at least:
function doIt() {
var elem = window.parent.document.getElementById('myIframe'); // the id of your iframe of course
elem.style.height = '40em';
}
I assume both the page and your iframe are yours and have the same "origin".
6 Comments
height attribute actually isn't supported (in xhtml at least). Will try too look up some confirmation on that. Anyway, I prefer to do the styling via CSS rules, so that's why I'm manipulating these.I would solve this using window.postMessage. This sends an message from the iframe to the parent page containing the iframe. Then you can update the height in the parent. Trying to set the height from within the iframe gives really nasty browser XSS prevention limitations.
A nice example is here:
parent:
// Every two seconds....
setInterval(function() {
// Send the message "Hello" to the parent window
// ...if the domain is still "davidwalsh.name"
parent.postMessage("Hello","http://davidwalsh.name");
},1000);
iframe:
// 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) {
console.log('parent received message!: ',e.data);
},false);