如何调整跨域url中iframe的大小

How to resize the iframe in cross domain url

本文关键字:url iframe 何调整 调整      更新时间:2023-09-26

任何人都能告诉我正在尝试在iframe加载函数is中加载url吗?我想在没有滚动条的情况下显示iframe并根据其内容进行调整,但父页面将根据内容进行滚动。有人能告诉我如何在跨域url中调整iframe的大小吗?

感谢

为了根据其内容调整iframe的大小,您不能使用postMessage将当前iframe高度发送给其父级。

iFrame中包含的页面需要使用postMessage将其当前高度发送到包含页面。include页面必须侦听该消息,并相应地更改iframe的高度。

附带页面中的代码可能看起来像这样:

function getBottom() {
    var max = jQuery("body").height();
    //Your additional calculations go here
    return max;
}
function updateHeight() {
    sendHeightToParent();
    setTimeout(updateHeight, 500);
}
function sendHeightToParent() {
    var messageObject = {
        "type":"size",
        "version":"1.0.0",
        "params":{
            "height": getBottom()
        }
    };
    //YOURTARGET is the target page if known. Otherwise use "*"
    parent.postMessage(JSON.stringify(messageObject), "YOURTARGET");
}
//Only possible if html5 post message is available
if (typeof parent.postMessage == 'function') {
    jQuery().ready(function() {
        sendHeightToParent();
        setTimeout(updateHeight, 500);
    });
}

然后,父级侦听事件并相应地更新iframe:

//Only possible if html5 post message is available
if (typeof parent.postMessage == 'function') {
    window.addEventListener("message", function (e) {
        obj = JSON.parse(e.data);
        if (obj.type == 'size') {
            myFrame = document.getElementById('YouIFrameId');
            myFrame.stye.height = obj.params.height + "px";
        }
    }
}