我正在开发一个类似igoogle的应用程序。来自其他应用程序(在其他域中)的内容使用iframe显示。

我如何调整iframes的大小以适应iframes的内容的高度?

我试图破译的javascript谷歌使用,但它是模糊的,搜索网络至今一无所获。

更新:请注意,内容是从其他域加载的,因此适用同源策略。


当前回答

我在这里读了很多答案,但几乎每个人都给出了一些交叉起源的框架块。

错误示例:

未捕获的DOMException:阻止了一个原点为“null”的帧 访问跨原点框架。

在相关线程中的答案也是一样的:

使iframe自动调整高度根据内容而不使用滚动条?

我不想使用第三方库,如iFrame Resizer或类似的库。

来自@ChrisJacob的答案很接近,但我缺少一个完整的工作示例,而不仅仅是链接。@Selvamani和@latitov也是很好的互补。

https://stackoverflow.com/a/3219970/3850405

我使用width="100%"的iframe,但代码可以修改为宽度以及工作。

这是我如何解决设置自定义高度的iframe:

iframe嵌入:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="description"
          content="Web site" />
    <title>Test with embedded iframe</title>
</head>
<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <iframe id="ifrm" src="https://localhost:44335/package/details?key=123" width="100%"></iframe>
    <script type="text/javascript">
        window.addEventListener('message', receiveMessage, false);

        function receiveMessage(evt) {
            console.log("Got message: " + JSON.stringify(evt.data) + " from origin: " + evt.origin);
            // Do we trust the sender of this message?
            if (evt.origin !== "https://localhost:44335") {
                return;
            }

            if (evt.data.type === "frame-resized") {
                document.getElementById("ifrm").style.height = evt.data.value + "px";
            }
        }
    </script>
</body>
</html>

iframe源代码,示例来自创建React应用程序,但只使用HTML和JS。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="description"
          content="Web site created using create-react-app" />
    <title>React App</title>
</head>
<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script type="text/javascript">
        //Don't run unless in an iframe
        if (self !== top) {
            var rootHeight;
            setInterval(function () {
                var rootElement = document.getElementById("root");
                if (rootElement) {
                    var currentRootHeight = rootElement.offsetHeight;
                    //Only send values if height has changed since last time
                    if (rootHeight !== currentRootHeight) {
                        //postMessage to set iframe height
                        window.parent.postMessage({ "type": "frame-resized", "value": currentRootHeight }, '*');
                        rootHeight = currentRootHeight;
                    }
                }
            }
                , 1000);
        }
    </script>
</body>
</html>

带有setInterval的代码当然可以修改,但它与动态内容一起工作得非常好。setInterval仅在内容嵌入iframe时激活,postMessage仅在高度改变时发送消息。

你可以在这里阅读更多关于Window.postMessage()的内容,但描述非常适合我们想要实现的目标:

The window.postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it. Normally, scripts on different pages are allowed to access each other if and only if the pages they originate from share the same protocol, port number, and host (also known as the "same-origin policy"). window.postMessage() provides a controlled mechanism to securely circumvent this restriction (if used properly).

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

其他回答

找不到能完美处理大文本+大图像的东西,但我最终得到了这个,似乎这是对的,或者几乎是对的,每一次:

    iframe.addEventListener("load",function(){
        // inlineSize, length, perspectiveOrigin, width
        let heightMax = 0;
        // this seems to work best with images...
        heightMax = Math.max(heightMax,iframe.contentWindow.getComputedStyle(iframe.contentWindow.document.body).perspectiveOrigin.split("px")[0]);
        // this seems to work best with text...
        heightMax = Math.max(heightMax,iframe.contentWindow.document.body.scrollHeight);
        // some large 1920x1080 images always gets a little bit off on firefox =/
        const isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
        if(isFirefox && heightMax >= 900){
            // grrr..
            heightMax = heightMax + 100;
        }

        iframe.style.height = heightMax+"px";
        //console.log(heightMax);
    });

<html>
<head>
<script>
function frameSize(id){
var frameHeight;

document.getElementById(id).height=0 + "px";
if(document.getElementById){
    newheight=document.getElementById(id).contentWindow.document.body.scrollHeight;    
}

document.getElementById(id).height= (frameHeight) + "px";
}
</script>
</head>

<body>

<iframe id="frame"  src="startframe.html" frameborder="0" marginheight="0" hspace=20     width="100%" 

onload="javascript:frameSize('frame');">

<p>This will work, but you need to host it on an http server, you can do it locally.    </p>
</body>
</html>

如果您可以控制iframe内容,我强烈建议使用

调整观察者大小

只需在iframe的srcdoc属性的末尾插入以下内容, 如果需要,可以转义。

<script type="text/javascript">
var ro = new ResizeObserver(entries => {
  for (let entry of entries) {
    const cr = entry.contentRect;
    // console.log(window.frameElement);
    window.frameElement.style.height =cr.height +30+ "px";
  }
});

ro.observe(document.body);
</script>

https://getbootstrap.com/docs/4.0/utilities/embed/

经过大量的研究,我明白了,这不是一个独特的问题,我打赌Bootstrap处理它。你瞧……

使用jQuery的最简单方法:

$("iframe")
.attr({"scrolling": "no", "src":"http://www.someotherlink.com/"})
.load(function() {
    $(this).css("height", $(this).contents().height() + "px");
});