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

标签 javascript angularjs iframe

任何人都可以告诉我正在尝试在 iframe onload 函数中加载 url 吗?我想显示没有滚动条的 iframe 并调整其内容,但父页面将根据内容滚动任何人都可以告诉如何调整 iframe 的大小跨域网址?

谢谢

最佳答案

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

包含在 iFrame 内的页面需要使用 postMessage 将其当前高度发送到包含页面。 包含页面必须监听该消息并相应地更改 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";
        }
    }
}

关于javascript - 如何调整跨域url中iframe的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37019790/

相关文章:

javascript - 从 id 数组到名称数组(mongo、nodejs)

javascript - AngularJS:如何从其他 JSON 中搜索并替换/添加 JSON 对象中的键?

javascript - AngularJS : continue execution in a controller once a looped service method has ended

javascript - 调整 iframe 滚动到屏幕分辨率的高度

javascript - 从它的子 IFRAME 中删除一个 DIV(跨域)

javascript - 抑制 onChange 触发 react

javascript - 如何使用js自动下载PDF?

javascript - 如何用canvas画一条可以向左移动的曲线?

javascript - AngularJs 中 KnockoutJs 的 WITH 的等效 html 属性是什么

google-chrome - 2020 年 8 月 10 日更新后,Chrome 不会在 iframe 中发回 cookie