我需要一个自动调整iframe的宽度和高度的解决方案,以勉强适应其内容。关键是宽度和高度可以在iframe加载后改变。我想我需要一个事件动作来处理iframe中包含的主体尺寸的变化。


当前回答

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

错误示例:

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

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

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

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

来自@bboydflo的答案很接近,但我缺少一个完整的示例。https://stackoverflow.com/a/52204841/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设置100%的宽度和高度,我会这样做:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="description"
          content="Web site" />
    <style>
        body {
            margin: 0; /* Reset default margin */
        }

        iframe {
            display: block; /* iframes are inline by default */
            background: #000;
            border: none; /* Reset default border */
            height: 100vh; /* Viewport-relative units */
            width: 100vw;
        }
    </style>
    <title>Test with embedded iframe</title>
</head>
<body>
    <iframe src="https://localhost:44335/package/details?key=123"></iframe>
</body>
</html>

来源:

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

其他回答

如果iframe内容来自相同的域,这应该工作得很好。但是它确实需要jQuery。

$('#iframe_id').load(function () {
    $(this).height($(this).contents().height());
    $(this).width($(this).contents().width());
});

要动态调整它的大小,你可以这样做:

<script language="javaScript">
<!--
function autoResize(){
    $('#themeframe').height($('#themeframe').contents().height());
}
//-->
</script>
<iframe id="themeframe" onLoad="autoResize();" marginheight="0" frameborder="0" src="URL"></iframe>

然后在iframe加载的页面上添加这个:

<script language="javaScript">
function resize()
{
    window.parent.autoResize();
}

$(window).on('resize', resize);
</script>
<script type="application/javascript">

function resizeIFrameToFitContent( iFrame ) {

    iFrame.width  = iFrame.contentWindow.document.body.scrollWidth;
    iFrame.height = iFrame.contentWindow.document.body.scrollHeight;
}

window.addEventListener('DOMContentLoaded', function(e) {

    var iFrame = document.getElementById( 'iFrame1' );
    resizeIFrameToFitContent( iFrame );

    // or, to resize all iframes:
    var iframes = document.querySelectorAll("iframe");
    for( var i = 0; i < iframes.length; i++) {
        resizeIFrameToFitContent( iframes[i] );
    }
} );

</script>

<iframe src="usagelogs/default.aspx" id="iFrame1"></iframe>

我使用这段代码自动调整所有iframe(类autoHeight)的高度,当他们加载在页面上。经过测试,它可以在IE, FF, Chrome, Safari和Opera中工作。

function doIframe() {
    var $iframes = $("iframe.autoHeight"); 
    $iframes.each(function() {
        var iframe = this;
        $(iframe).load(function() {
            setHeight(iframe);
        });
    });
}

function setHeight(e) {
  e.height = e.contentWindow.document.body.scrollHeight + 35;
}

$(window).load(function() {
    doIframe();
});
function resizeIFrameToFitContent(frame) {
if (frame == null) {
    return true;
}

var docEl = null;
var isFirefox = navigator.userAgent.search("Firefox") >= 0;

if (isFirefox && frame.contentDocument != null) {
    docEl = frame.contentDocument.documentElement;
} else if (frame.contentWindow != null) {
    docEl = frame.contentWindow.document.body;
}

if (docEl == null) {
    return;
}

var maxWidth = docEl.scrollWidth;
var maxHeight = (isFirefox ? (docEl.offsetHeight + 15) : (docEl.scrollHeight + 45));

frame.width = maxWidth;
frame.height = maxHeight;
frame.style.width = frame.width + "px";
frame.style.height = frame.height + "px";
if (maxHeight > 20) {
    frame.height = maxHeight;
    frame.style.height = frame.height + "px";
} else {
    frame.style.height = "100%";
}

if (maxWidth > 0) {
    frame.width = maxWidth;
    frame.style.width = frame.width + "px";
} else {
    frame.style.width = "100%";
}
}

iFram风格:

.myIFrameStyle {
   float: left;
   clear: both;
   width: 100%;
   height: 200px;
   padding: 5px;
   margin: 0px;
   border: 1px solid gray;
   overflow: hidden;
}

iframe的日子:

<iframe id="myIframe" src="" class="myIFrameStyle"> </iframe>

脚本标签:

<script type="text/javascript">
   $(document).ready(function () {
      $('myIFrame').load(function () {
         resizeIFrameToFitContent(this);
      });
    });
</script>

如果你可以控制IFRAME内容和父窗口,那么你需要IFRAME调整器。

这个库允许自动调整相同域和跨域iframe的高度和宽度,以适应它们所包含的内容。它提供了一系列功能来解决使用iFrames时最常见的问题,包括:

Height and width resizing of the iFrame to content size. Works with multiple and nested iFrames. Domain authentication for cross domain iFrames. Provides a range of page size calculation methods to support complex CSS layouts. Detects changes to the DOM that can cause the page to resize using MutationObserver. Detects events that can cause the page to resize (Window Resize, CSS Animation and Transition, Orientation Change and Mouse events). Simplified messaging between iFrame and host page via postMessage. Fixes in page links in iFrame and supports links between the iFrame and parent page. Provides custom sizing and scrolling methods. Exposes parent position and viewport size to the iFrame. Works with ViewerJS to support PDF and ODF documents. Fallback support down to IE8.