简体   繁体   中英

autoresize iframe in another domain according to its content

I am having an iframe which will load content from different domain. I want to adjust the height of the iframe automatically depending on the height of it's content.

I have used post message but it is adjusting the height of iframe according to the window's height.

Here is my code:

 var length;
 var myEventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
 var myEventListener = window[myEventMethod];
 var myEventMessage = myEventMethod == "attachEvent" ? "onmessage" : "message";

 myEventListener(myEventMessage, function (e) {
     var y=document.getElementById(e.data.Id);
     var x = e.data.Height;
     y.height = x;
 }, false);

 document.addEventListener('DOMContentLoaded', function () {
     var widgets = document.getElementsByClassName('Container');
     length = widgets.length
     for (var i = 0, len = length; i < len; i++) {
        var url = widgets[i].getAttribute("data-url");
        var element = document.createElement("iframe");
        element.setAttribute("src", url);
        element.setAttribute("id", "Iframe" + i);
        widgets[i].appendChild(element);
        var a = { "Id": "Iframe" + i, "Height": document.body.scrollHeight }
        window.parent.postMessage(a, "*")
    }

 }, false);

Here I am using document.body.scrollHeight (current winodw's height) instead I want iframe's body's height.

/* client.js */   
function adjust_iframe_height(){
var iframeContainerH = $('#iframecontainer').height();
exactHeight = iframeContainerH +10;// Fetches the div content height 

window.parent.postMessage(exactHeight,"*"); // allows this to post to any parent iframe regardless of domain
}
$(window).resize(function(){ // Use document ready if needed
    setTimeout(function(){adjust_iframe_height()}, 2000); // Time Out Set for 5 sec to    ensure that it is called after bootstrap auto alignment on resize
});
/* parent.js */
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent, function(e) {
    document.getElementById('frame1').height = e.data + 'px';
}, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM