Is there a cross-domain iframe height auto-resizer that works?

后端 未结 7 2420
暖寄归人
暖寄归人 2020-11-27 09:41

I tried a few solutions but wasn\'t successful. I\'m wondering if there is a solution out there preferably with an easy-to-follow tutorial.

7条回答
  •  旧时难觅i
    2020-11-27 10:33

    I got the solution for setting the height of the iframe dynamically based on it's content. This works for the cross domain content. There are some steps to follow to achieve this.

    1. Suppose you have added iframe in "abc.com/page" web page

    2. Next you have to bind windows "message" event under web page "abc.com/page"

    window.addEventListener('message', function (event) {
    //Here We have to check content of the message event  for safety purpose
    //event data contains message sent from page added in iframe as shown in step 3
    if (event.data.hasOwnProperty("FrameHeight")) {
            //Set height of the Iframe
            $("#IframeId").css("height", event.data.FrameHeight);        
        }
    });
    

    On iframe load you have to send message to iframe window content with "FrameHeight" message:

    function setIframeHeight(ifrm) {
       var height = ifrm.contentWindow.postMessage("FrameHeight", "*");   
    }
    
    1. On main page that added under iframe here "xyz.pqr/contactpage" you have to bind windows "message" event where all messages are going to receive from parent window of "abc.com/page"
    window.addEventListener('message', function (event) {
    
        // Need to check for safety as we are going to process only our messages
        // So Check whether event with data(which contains any object) contains our message here its "FrameHeight"
       if (event.data == "FrameHeight") {
    
            //event.source contains parent page window object 
            //which we are going to use to send message back to main page here "abc.com/page"
    
            //parentSourceWindow = event.source;
    
            //Calculate the maximum height of the page
            var body = document.body, html = document.documentElement;
            var height = Math.max(body.scrollHeight, body.offsetHeight,
                html.clientHeight, html.scrollHeight, html.offsetHeight);
    
           // Send height back to parent page "abc.com/page"
            event.source.postMessage({ "FrameHeight": height }, "*");       
        }
    });
    

提交回复
热议问题