Thursday, October 13, 2011

How To: Stretch an iFrame to the size of its contents

I had a requirement to put a PageViewerControl inside a SharePoint 2007 page (which is rendered out as an iFrame) and the height of it must be set to the height of its contents. Now most browsers won't allow you to do this at all for security reasons and I would suggest finding another way to build this, but during my development I did get this little script working on a lot of the more common browsers. Not sure how it will do on IE8 or IE9 though...

<script type="text/javascript">
 // get the iframe
 var oFrame = document.getElementsByTagName("iframe")[0];

 function SetFrameHeight_FireFox(){ 
  try{
   // remove border and scrolling
   oFrame.setAttribute("frameborder","0");
   oFrame.setAttribute("scrolling","no");
 
   // set height and width
   var oBody = oFrame.contentWindow.document.body;
   document.getElementById("ifrm").style.height = oBody.scrollHeight + "px";
   document.getElementsByTagName("iframe")[0].style.width = "960px";
  }
  catch(e){
   window.status =  'Error: ' + e.number + '; ' + e.description;
  }
 }

 function SetFrameHeight_IE(){
  try{
   // set height and width
   var oBody = oFrame.document.body;
   document.getElementById("ifrm").style.height = ifrm.document.body.scrollHeight + (ifrm.document.body.offsetHeight - ifrm.document.body.clientHeight);
   document.getElementsByTagName("iframe")[0].style.width = "960px";
  
   // remove scrolling
   ifrm.document.body.setAttribute('scroll', 'no');
  }
  catch(e){
   window.status =  'Error: ' + e.number + '; ' + e.description;
  }
 }

 // check for browser type and call function when frame has finished loading.
 if(document.implementation && document.implementation.createDocument)
 {
  oFrame.setAttribute("onLoad","SetFrameHeight_FireFox()");
 }
 else
 {
  oFrame.setAttribute("onload","SetFrameHeight_IE()");
 
 }
</script>

No comments:

Post a Comment