11

Both main window and iframe are on the same domain, but what I want to achieve is to resize iframe to fit its contents using js only within that iframe.

I also do not know the id of the iframe that is assigned to it by main window. And I do not want to use jquery or any other framework for it.

asked Aug 4, 2012 at 7:59

3 Answers 3

14

You can do this also without knowing the idof the iframe in the parent window:

window.frameElement.style.width = iframeContentWidth + 'px';
window.frameElement.style.height = iframeContentHeight + 'px';

See frameElement at MDN.

EDIT

Just in case the iframe happens to be in a container element which has fixed size and overflow: hidden you can do something like this:

function resizeIframe (iframeContentWidth, iframeContentHeight) {
 var container = window.frameElement.parentElement;
 if (container != parent.document.body) {
 container.style.width = iframeContentWidth + 'px';
 container.style.height = iframeContentHeight + 'px';
 }
 window.frameElement.style.width = iframeContentWidth + 'px';
 window.frameElement.style.height = iframeContentHeight + 'px';
 return;
}
answered Aug 4, 2012 at 8:57
Sign up to request clarification or add additional context in comments.

Comments

0

For same-origin content like yours, yes you can.

To borrow from Gary's answer on the above question:

In the iframe, window.parent refers to the global object of the parent document, not the document object itself. I believe you would need to use parent.document.getElementById

Try accessing the iframe using parent.document, and see if this solves your issue.

answered Aug 4, 2012 at 8:42

Comments

0

Assuming you have only 1 IFRAME in the main window, from the Javascript of the IFRAME's document you can do something like:

function getMySelf()
{
 return (window.parent.document.getElementsByTagName("iframe"))[0];
}
var myself = getMySelf();
myself.style.width = whateverWidth;
myself.style.height = whateverHeight;
answered Aug 4, 2012 at 9:57

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.