Hi I'm trying to find a script that dynamically resizes the iframe to be the height of the page contained within it

The iframe page I am accessing is an external domain page.

I know due to security reasons normally all external pages loaded into the iframe must be from the same domain as the page the iframe tag is inserted. My twist is I can add codes to the external domain source page. I was wondering in this case is there a way to work around this issue so I can dynamically resize my parent iframe?

This is the closest thing I found, except it doesn't work for external pages on different domains.
http://www.dynamicdrive.com/dynamicindex17/iframessi2.htm

Thanks much!!

Recommended Answers

All 14 Replies

Not really the solution you are looking for, but you could use a php script to cache the pages locally on your server. What are you trying to do exactly. I would be very careful using content from someone elses sight in this way....

Dance

Thanks for the tip. I don't know much about php but I will research...

Actually I'm trying to pull external content into my site - legally, of course. I do have the permission to do so from the external domain. Their page height fluctuates though, so I wanted to see if I can make my iframe height change dynamically to fix all of their content without scroll bar.

I guess I can just ask the external site people to give me an estimate of what their longest pages are, so I can set my iframe to the maximum height.

This should work for you:

<?php
// Edit these...
$page_to_cache = "http://www.theirdomain.com/pagetocache.html";
$page_to_write = 'mycachedpage.html';

// Do not edit below...
$cache = file_get_contents($page_to_cache);

$fh = fopen($page_to_write, 'wt');
fwrite($fh, $cache);
fclose($fh);

?>

You can contact your host to setup a cron job, or possibly do it in the cpanel.

Dance

Is there a way to get the height of the iframe without catching the file (im using local websites in my iframe) but i want to resize a cell in my table to the height of the page in the iframe. is this possible?

dance instructor> Thanks for the code. Our site doesn't work with cache (due to other code/database related issues) so we ended up just asking the external site to tell us their best guess of page height.

shiznatix> If you go to http://www.dynamicdrive.com/dynamicindex17/iframessi2.htm the code there should help you - I think...

I think it was already mentioned here but I am pulling out my hair as well...

My problem is, that I want the iframe to adapt the hight of the importet document WITHOUT there being scrollbars but the iframe adapting to the hight of the document.

My first tries went towards my coppermine gallery which is on THIS soul server in my house but yet under a different v-host. None the less... I read, that external URLs would not work because iframe couldn't figure out how high the imported document is...

Having read this I was rather demotivated but went ahead and built all the documents into the wwwroot which made them "local" BUT still no working iframe as I'd define it beacuse the doc - even when loaded locally - still has scroll bars to it.

Now I don't know what to do and where I went wrong and would be very happy, if anyone could help me out here.

Regards

Lars Hilse

Yes... but I wasn't able to make it work... what else to I have to look upon while writing the script?

The page is located at http://hg2.serveftp.net/larhil2 - could be, that it is quite a mess by now.

Well, yes, some things are quite a mess. I'm particularly worried about your unclosed

<body onload="goSetHeight()">

in the middle of the page, that is a HUGE no-no.

A web page can only have 1 <body> declaration, and your is a few lines back:

<body onload="MM_preloadImages('imagetank/button02.jpg','imagetank/button02-PHOTO.jpg','imagetank/button02-WEB.jpg','imagetank/button02-HOME.jpg')">

To have both onload requests merge you would want to delete the <body> in the middle of the page and change the first one to:

<body onload="MM_preloadImages('imagetank/button02.jpg','imagetank/button02-PHOTO.jpg','imagetank/button02-WEB.jpg','imagetank/button02-HOME.jpg'); goSetHeight()">

But before the goSetHeight() call can work, you first need to add to your page a goSetHeight() function declaration along with all the scripting found at the link I gave you.

I would also STRONGLY encourage you to remake the page from scratch. Some parts are terribly messy and are bound to hurt the render in one browser or the other.

Hello all.. I found this thread when trying to solve my problem with iframes..

I am using the javascript code from http://www.dyn-web.com/dhtml/iframes/height.html

The problem that I am having is that the iframe opens with a scrollbar, but I want the iframe to be set to the sub page's height..

I have linked the javascript for this function in a separate file (which every page links to), and also included the
onload="goSetHeight()" as well as the

function goSetHeight() {
  if (parent == window) return;
  // arg: id of iframe element this doc is to be loaded into
  else parent.setIframeHeight('ifrm');

}

into every document, but still - SCROLLBARS APPEAR!

The document(s) in question can be located at:

http://www.hyperoctave.org/new%20index%202007%20F.htm

In the scrolling navigation frame, the "New artist: Scrape.dx - 23/06/06" link is the one I've been testing the script on. Click that to see what I mean.

I am using Mozilla Firefox.

      http://www.hyperoctave.org/scrapedxnew2.htm

Any suggestions? I've been troubleshooting this for days now!

Little buggy but concept works. You will need to add a javascript to the iframed content pages.

From: http://geekswithblogs.net/rashid/archive/2007/01/13/103518.aspx

// FrameManager.js -- Must be added in Hosting windowvar FrameManager ={    currentFrameId : '',    currentFrameHeight : 0,    lastFrameId : '',    lastFrameHeight : 0,    resizeTimerId : null,    init : function()    {        if (FrameManager.resizeTimerId == null)        {            FrameManager.resizeTimerId = window.setInterval(FrameManager.resizeFrames, 500);        }    },    resizeFrames : function()    {        FrameManager.retrieveFrameIdAndHeight();        if ((FrameManager.currentFrameId != FrameManager.lastFrameId) ||            (FrameManager.currentFrameHeight != FrameManager.lastFrameHeight))        {            var iframe = document.getElementById(FrameManager.currentFrameId.toString());            if (iframe == null) return;            iframe.style.height = FrameManager.currentFrameHeight.toString() + "px";            FrameManager.lastFrameId = FrameManager.currentFrameId;            FrameManager.lastFrameHeight = FrameManager.currentFrameHeight;            window.location.hash = '';        }    },    retrieveFrameIdAndHeight : function()    {        if (window.location.hash.length == 0) return;        var hashValue = window.location.hash.substring(1);        if ((hashValue == null) || (hashValue.length == 0)) return;        var pairs = hashValue.split('&');        if ((pairs != null) && (pairs.length > 0))        {            for(var i = 0; i < pairs.length; i++)            {                var pair = pairs[i].split('=');                if ((pair != null) && (pair.length > 0))                {                    if (pair[0] == 'frameId')                    {                        if ((pair[1] != null) && (pair[1].length > 0))                        {                            FrameManager.currentFrameId = pair[1];                        }                    }                    else if (pair[0] == 'height')                    {                        var height = parseInt(pair[1]);                        if (!isNaN(height))                        {                            FrameManager.currentFrameHeight = height;                            FrameManager.currentFrameHeight += 15;                        }                    }                }            }        }    },    registerFrame : function(frame)    {        var currentLocation = location.href;        var hashIndex = currentLocation.indexOf('#');        if (hashIndex > -1)        {            currentLocation = currentLocation.substring(0, hashIndex);        }        frame.contentWindow.location = frame.src + '?frameId=' + frame.id + '#' + currentLocation;    }};window.setTimeout(FrameManager.init, 300);<!--Host.html-Where the Target iframe resides--><html xmlns="http://www.w3.org/1999/xhtml" ><head>    <title>IFrame Resize Sample</title>    <script type="text/javascript" src="FrameManager.js"></script></head><body>    <div>The Following is an iframe:</div>    <iframe id="ifrSample1" scrolling="no" frameborder="0" src="Frame.html" style="margin:0px;width:330px;height:100px" onload="FrameManager.registerFrame(this)"></iframe></body></html>// Frame.js -- Must be added in iframe windowfunction publishHeight(){    if (window.location.hash.length == 0) return;    var frameId = getFrameId();    if (frameId == '') return;    var actualHeight = getBodyHeight();    var currentHeight = getViewPortHeight();    if  (Math.abs(actualHeight - currentHeight) > 15)    {        var hostUrl = window.location.hash.substring(1);        hostUrl += "#";        hostUrl += 'frameId=' + frameId;        hostUrl += '&';        hostUrl += 'height=' + actualHeight.toString();        window.top.location = hostUrl;    }}function getFrameId(){    var qs = parseQueryString(window.location.href);    var frameId = qs["frameId"];    var hashIndex = frameId.indexOf('#');    if (hashIndex > -1)    {        frameId = frameId.substring(0, hashIndex);    }    return frameId;}function getBodyHeight(){    var height;    var scrollHeight;    var offsetHeight;    if (document.height)    {        height = document.height;    }    else if (document.body)    {        if (document.body.scrollHeight)        {            height = scrollHeight = document.body.scrollHeight;        }        if (document.body.offsetHeight)        {            height = offsetHeight = document.body.offsetHeight;        }        if (scrollHeight && offsetHeight)        {            height = Math.max(scrollHeight, offsetHeight);        }    }    return height;}function getViewPortHeight(){    var height = 0;    if (window.innerHeight)    {        height = window.innerHeight - 18;    }    else if ((document.documentElement) && (document.documentElement.clientHeight))    {        height = document.documentElement.clientHeight;    }    else if ((document.body) && (document.body.clientHeight))    {        height = document.body.clientHeight;    }    return height;}function parseQueryString(url){    url = new String(url);    var queryStringValues = new Object();    var querystring = url.substring((url.indexOf('?') + 1), url.length);    var querystringSplit = querystring.split('&');    for (i = 0; i < querystringSplit.length; i++)    {        var pair = querystringSplit[i].split('=');        var name = pair[0];        var value = pair[1];        queryStringValues[name] = value;    }    return queryStringValues;}<!--Frame.html-Will reside in another domain--><html xmlns="http://www.w3.org/1999/xhtml" ><head>    <title>Page In IFrame</title>    <script type="text/javascript" src="Frame.js"></script>    <script type="text/javascript">        window.onload = function(event)        {            window.setInterval(publishHeight, 300);        }    </script></head><body>    <div>        <div style="padding:4px;border:solid 1px #cccccc;width:300px">            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce in tortor sit amet sem luctus ornare. Nam sed augue id erat commodo gravida. Nulla in pede. Nunc sed elit non pede aliquam eleifend. Cras varius. Sed non lorem eget ipsum accumsan suscipit. Donec bibendum enim. Phasellus a ligula. Fusce turpis diam, ultricies at, ullamcorper a, consectetuer et, mauris. Pellentesque neque felis, scelerisque non, vestibulum at, luctus quis, velit. Quisque sit amet mi sed sem facilisis ornare. In leo ante, hendrerit nec, lobortis eget, feugiat ac, orci.        </div>        <div style="padding:4px;border:solid 1px #cccccc;width:300px">            Maecenas ullamcorper ornare urna. Sed ornare leo vel lorem pretium ornare. Sed vitae lacus eu pede molestie venenatis. Morbi vestibulum. Proin tincidunt, sem sit amet semper volutpat, nulla ante pulvinar turpis, ut porta turpis augue sit amet magna. Nam in mauris. In mauris. Nunc metus. Duis eget diam. Sed vulputate lacus eget ipsum. Etiam ultricies bibendum ligula. Mauris semper, magna nec posuere pretium, quam lectus ultricies magna, ac pharetra risus ligula at dui. Integer volutpat sagittis ipsum.        </div>        <div style="padding:4px;border:solid 1px #cccccc;width:300px">            Cras pretium. Morbi condimentum. Morbi leo dui, hendrerit non, rhoncus vitae, ultrices sed, quam. Praesent sit amet quam non turpis pellentesque egestas. Aliquam odio lacus, condimentum eu, tempus eget, porta ac, ipsum. Phasellus sit amet mauris at nisl lobortis aliquet. Suspendisse fringilla metus porta lacus. Nam aliquet. Sed vestibulum tellus ac leo. Nunc sed metus vel nisl ultricies fermentum. Maecenas aliquam ligula quis est venenatis mattis. Suspendisse sollicitudin aliquet leo. Quisque condimentum felis ac nisl. Curabitur bibendum, pede et venenatis ornare, massa justo ullamcorper velit, a rutrum tellus mi et ligula. Maecenas nibh libero, faucibus vel, lacinia ac, laoreet nec, odio. Quisque dui quam, vestibulum sit amet, convallis eget, fermentum nec, mauris. Vivamus et massa ut orci pellentesque consectetuer. Proin dolor arcu, ornare non, iaculis eu, aliquam sed, quam. Morbi volutpat semper ipsum.        </div>        <div style="padding:4px;border:solid 1px #cccccc;width:300px">            Suspendisse potenti. Praesent eu turpis. Nullam nulla sem, sollicitudin lacinia, laoreet rhoncus, commodo nec, nisl. Nam pharetra porta justo. Etiam faucibus, turpis eu dapibus varius, felis nibh tempus justo, sed faucibus metus dolor nec leo. Sed rutrum, sapien eget placerat accumsan, enim quam porttitor leo, ac aliquam felis elit non enim. Sed dapibus nonummy massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean sagittis, metus et hendrerit aliquam, ligula turpis nonummy diam, id interdum risus ligula et magna. Phasellus vel nibh in lorem pretium iaculis.        </div>        <div style="padding:4px;border:solid 1px #cccccc;width:300px">            Proin mattis pharetra libero. Morbi varius, nunc laoreet blandit porttitor, pede augue condimentum felis, ac varius libero nibh eu est. Mauris condimentum arcu eget dolor. Phasellus vitae ipsum vel tellus feugiat lacinia. Quisque leo diam, porta id, commodo quis, ornare vitae, massa. In cursus dictum ante. In hac habitasse platea dictumst. Donec volutpat sem nec mauris. Donec venenatis lorem eget quam. Curabitur vitae ipsum sit amet augue dignissim ultricies. Maecenas eget velit. Donec nec tellus at lectus rhoncus ultricies.        </div>    </div></body></html>

Hello, please I need to understand how iFrames work, so i can follow up on this thread. anyone?

in hindsight, I have discovered that PHP is much better for this kind of thing. Iframes just cannot do what the PHP include tag can do..

it works thus:

In your master page (lets call it index), insert into the head of your HTML document:

<?php 
  
$page= $_GET["page"];                                                 //get the variable from the URL
 $subcode = file_get_contents($page);                     //load the file into a variable

?>

then, at the location in that page where you want the subpage to show:

<div id="sub_content">

<?php echo($subcode) ?>

</div>

save the file as a .PHP file.. Now when you open your file, it will have a blank field where the <div id="sub_content"> is, but if you open your file, with the subpage in it, eg:
index.php?page=subpage.htm

the sub page will appear at that section, and if you view the source code in your browser, it will appear to be one entire page.

The sub page does not have to have any headers, CSS or Javascript, since (if you use them) these will be embedded in the master page! You will also want your subpage to 'fit' into your master page - I limit the width to 500px to keep everything uniform.

Here is another neat trick, to avoid people opening up your subpages:

Insert into your subpage:

<script language = "Javascript" type = "text/javascript">
if (top.location == self.location)
{
self.location.replace ("index.php?page=subpage.htm")
}
</script>

as you can quite obviously see, if the page that is being opened is the parent, then the browser is told to open the master page, with the subpage in it..

See it in action at www.hyperoctave.org
you will see that index.htm is instantly referred to index.php?page=camo_cymbol.htm (or something similar).. the subpage is on the right hand side. You can click other links in that page to open up other subpages at the location I have set.

A little bit of research, and trying to solve my problem, has led to this invaluable solution. And it really is that easy when you know how!

Actually i discovered this bit a long time ago.. it's effect is.. well.. similar to that of AJAX...

The problem with us programmers sometimes is that when we get to engrossed, we keep forgetting that the solution is as simple as what you showed us here.. thank you for reminding us that we are still human.. more power dude!

in hindsight, I have discovered that PHP is much better for this kind of thing. Iframes just cannot do what the PHP include tag can do..

it works thus:

In your master page (lets call it index), insert into the head of your HTML document:

<?php 
  
$page= $_GET["page"];                                                 //get the variable from the URL
 $subcode = file_get_contents($page);                     //load the file into a variable

?>

then, at the location in that page where you want the subpage to show:

<div id="sub_content">

<?php echo($subcode) ?>

</div>

save the file as a .PHP file.. Now when you open your file, it will have a blank field where the <div id="sub_content"> is, but if you open your file, with the subpage in it, eg:
index.php?page=subpage.htm

the sub page will appear at that section, and if you view the source code in your browser, it will appear to be one entire page.

The sub page does not have to have any headers, CSS or Javascript, since (if you use them) these will be embedded in the master page! You will also want your subpage to 'fit' into your master page - I limit the width to 500px to keep everything uniform.

Here is another neat trick, to avoid people opening up your subpages:

Insert into your subpage:

<script language = "Javascript" type = "text/javascript">
if (top.location == self.location)
{
self.location.replace ("index.php?page=subpage.htm")
}
</script>

as you can quite obviously see, if the page that is being opened is the parent, then the browser is told to open the master page, with the subpage in it..

See it in action at www.hyperoctave.org
you will see that index.htm is instantly referred to index.php?page=camo_cymbol.htm (or something similar).. the subpage is on the right hand side. You can click other links in that page to open up other subpages at the location I have set.

A little bit of research, and trying to solve my problem, has led to this invaluable solution. And it really is that easy when you know how!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.