Geeks With Blogs
Amit's Blog Sharing Thoughts and Learning

Recently I was trying to set an iframe height which is hosted in another domain. But could not able to get its height from its hosting window - It always throws security exception. I searched Google and found a interesting example on Iframe cross domain messaging, here is the link. Based upon it I have created a small solution which finally does the job. Here are files, you can also download these files from this link:

// FrameManager.js -- Must be added in Hosting window
var 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 window
function 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>

kick it on DotNetKicks.com

Posted on Saturday, January 13, 2007 11:40 PM iframe , Tips/Tricks | Back to top


Comments on this post: Cross Domain Iframe Resize

# re: Cross Domain Iframe Resize
Requesting Gravatar...
Hi,

Keen for a solution.

The page keeps refreshing. How do I stop that?

John G
Left by John Greenbury on Feb 05, 2007 12:26 PM

# re: Cross Domain Iframe Resize
Requesting Gravatar...
Seems to set the initial iframe height properly cross domain. Issue is when any link is clicked within the iframe the iframe resets to the original url.

Trying to iframe cross domain asp application with "http://crossdomain.url/generate.asp?varialble=x&morevariables=y" but no hash.

Seems to be an issue with the parsing of the URL string in frameManager.js file
Left by Samir on Feb 22, 2007 10:47 AM

# re: Cross Domain Iframe Resize
Requesting Gravatar...
How do I get this to work if I can't edit the framed page?
Left by Mark Figueredo on Jul 03, 2007 4:20 AM

# re: Cross Domain Iframe Resize
Requesting Gravatar...
Hi it works fine under IE but under Mozilla it still keeps refreshing and refreshing and refreshing ...
Have You got any idea how to make it working?
Left by Daniel on Oct 03, 2007 11:47 PM

# re: Cross Domain Iframe Resize
Requesting Gravatar...
Hi,

I tried this code in IE and am facing below issues.

1. Same page is loaded multiple times.

2. Navigation / redirection to subsequent page

Scenario:

I have a page "A" that contains "Add to cart" icon and when I click on "Add to cart", subsequent page "B" should be displayed

But, the application navigates / redirects to subsequent page "B" and returns back to page "A"

Appreciate any tips on the issues that I am facing

Thanks,
JGuru
Left by JGuru on Nov 15, 2007 7:56 PM

# re: Cross Domain Iframe Resize
Requesting Gravatar...
You guys seems as if you are playing here, nothing is working fine even when you open host.html it keeps on refreshing that's it.
one should always make sure while submitting a code it should be working, dont make assumptions.
Left by Jimmy on Dec 13, 2007 3:42 AM

# re: Cross Domain Iframe Resize
Requesting Gravatar...
Hey guys this answer not works advertised as while refreshing. You is nots assuming things thats should be proof-read by valid code make. Much appreciate serious more attitude would I.
Left by Bobby on Sep 03, 2008 11:58 PM

# re: Cross Domain Iframe Resize
Requesting Gravatar...
It will work for fine .net pages or not . Please let me know.
Left by Rushi Dole on Sep 07, 2008 5:16 PM

# re: Cross Domain Iframe Resize
Requesting Gravatar...
To stop refreshing page in Mozilla just change line in FrameManager.js :
from
> window.location.hash = '';
to
> window.location.hash = '#';

Marek
Left by Softika on Sep 12, 2008 6:01 PM

# re: Cross Domain Iframe Resize
Requesting Gravatar...
This code works perfectly.
Just try to understand it instead of crying on your mother.
Left by SL on Nov 03, 2008 5:05 PM

Your comment:
 (will show your gravatar)


Copyright © Kazi Manzur Rashid | Powered by: GeeksWithBlogs.net | Join free