0

I am using this script to resize iframe height and width automatically based on the content..

<script language="JavaScript">


function autoResize(id){
    var newheight;
    var newwidth;

    if(document.getElementById){
        newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
        newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
    }

    document.getElementById(id).height= (newheight) + "px";
    document.getElementById(id).width= (newwidth) + "px";
}
</script>

This script is not working in cross domain servers..Is there any alternate way?

UI_Dev
  • 3,317
  • 16
  • 46
  • 92

1 Answers1

0

I very recently had this issue myself. Finally I solved it with the postMessage method.

  1. In the document included to the iFrame I check whether it's actually running from an iFrame.

    function inIframe(){
        if(top != self){
             var contentHeight = $('#myIframeContent').height(); //Just this part I did with jQuery as I was sure that the document uses it
             postSize(contentHeight);
             }
        }
    
  2. If the document is running within an iFrame, call a function that we will call postSize.

    function postSize(height){
         var target = parent.postMessage ? parent : (parent.document.postMessage ? parent.document : undefined);
    
        if(typeof target != "undefined" && document.body.scrollHeight){
            target.postMessage(height, "*");
            }
        }
    
  3. Add the following code to the document that includes your iFrame

    function receiveSize(e){
        if(e.origin === "http://www.mywebsite.net"){
            var newHeight = e.data + 35;
            document.getElementById("myIframeID").style.height = newHeight + "px";
            }
        }
    
    window.addEventListener("message", receiveSize, false);
    

Unfortunately I cannot remember the exact sources of all this as I was viewing a lot of different solutions here on Stackoverflow, but also different websites. But this solution works good for me.

Someone else previously had this problem and I posted this solution here. It seemed to work fine for him as well: Error: Permission denied to access property 'document'

Cheers

Community
  • 1
  • 1
faerin
  • 1,915
  • 17
  • 31