Html 跨域 iframe 调整大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5908676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 08:27:58  来源:igfitidea点击:

cross-domain iframe resize

htmlcssscriptingiframecross-domain

提问by Piotr Kula

How do I resize an iframe from another domain

如何从另一个域调整 iframe 的大小

-Edit

-编辑

Scroll down for some solutions.. or read on how NOT to do this :D

向下滚动以获取一些解决方案......或阅读如何不这样做:D

After many hours of code hacking- the conclusion is that anything inside the iframe is not accessible, even the scrollbars that render on my domain. I have tried many techniques to no avail.

经过数小时的代码黑客攻击 - 结论是 iframe 中的任何内容都无法访问,即使是在我的域上呈现的滚动条。我尝试了很多技术都无济于事。

To save you time don't even go down this route just use sendMessages for cross domain communications.There are plug ins for HTML < 5 that I use- Go to the bottom for a nice example :)

为了节省您的时间,甚至不要走这条路,只需使用 sendMessages 进行跨域通信。我使用了 HTML < 5 的插件 - 转到底部的一个很好的例子:)



Past few days I have been trying to integrate an iframe into a site. This is a short term solution while the other side develops and API(could take months...) And because this is as short term solution we done want to use easyXDM- I have access to the other domain but its difficult enough asking them to add p3p header as it is.....

过去几天我一直在尝试将 iframe 集成到站点中。这是一个短期解决方案,而另一方开发和 API(可能需要几个月......)而且因为这是短期解决方案,我们确实想使用 easyXDM-我可以访问另一个域,但要求他们这样做已经够困难了按原样添加 p3p 标头.....

3 iframes

3 个 iframe

The closest solution I found was the 3 iframes- but it goes mental of chrome and safari so I cannot use that.

我找到的最接近的解决方案是 3 个 iframe,但它对 chrome 和 safari 很敏感,所以我不能使用它。

open in chrome

在 chrome 中打开

http://css-tricks.com/examples/iFrameResize/crossdomain.php#frameId=frame-one&height=1179

http://css-tricks.com/examples/iFrameResize/crossdomain.php#frameId=frame-one&height=1179

Measure the scrollbars

测量滚动条

I found a another post on how to use the scrollheight to try and resize the form.. in theory it works well but I could not apply it properly using the iframes scroll height..

我发现了另一篇关于如何使用滚动高度尝试调整表单大小的帖子..理论上它运行良好,但我无法使用 iframes 滚动高度正确应用它..

document.body.scrollHeight

That obvoisly uses the bodies height (cannot access these properties 100% is based on the clients display canvaz and not the x-domains document height)

显然使用主体高度(无法访问这些属性 100% 是基于客户端显示的画布而不是 x 域文档高度)

I tried using jquery to get the iframes height

我尝试使用 jquery 来获取 iframes 高度

$('#frameId').Height()

$('#frameId').clientHeight

$('#frameId').scrollHeight

return values different in chrome and ie - or just don't make sense at all. The problem is that everything inside the frame is denied- even the scrollbar...

在 chrome 和 ie 中返回不同的值 - 或者根本没有意义。问题是框​​架内的所有内容都被拒绝了 - 甚至滚动条......

Computed Styles

计算样式

But if I inspect and element in chrome of the iframe it bladdy shows me the documents dimensions inside the iframe (using jquery x-domain to get iframe.heigh - access denied) There is nothing in the computed CSS enter image description here

但是,如果我在 iframe 的 chrome 中检查和元素,它会向我显示 iframe 内的文档尺寸(使用 jquery x-domain 获取 iframe.heigh - 访问被拒绝)计算的 CSS 中没有任何内容 在此处输入图片说明

Now how does chrome calculate that? (edit- browser re-renders the page using its build in rendering engine to calcualte all these settings - but are not attached anywhere to prevent cross-domain fraud.. so..)

现在 chrome 是如何计算的?(编辑 - 浏览器使用其内置渲染引擎重新渲染页面以计算所有这些设置 - 但未附加到任何地方以防止跨域欺诈......所以......)

HTML4

HTML4

I read specification of HTML4.x and it says there that there should be read-only values exposed via document.element but it's access denied via jquery

我阅读了 HTML4.x 的规范,它说应该有通过 document.element 公开的只读值,但它通过 jquery 拒绝访问

Proxy Frame

代理帧

I went down the route of proxying the site back and calculating which is OK.. until a user logs in through the iframe and the proxy gets a login page instead of the actual content. Also to some calling the page twice is not acceptable

我沿着代理站点的路线返回并计算哪个可以。直到用户通过 iframe 登录并且代理获取登录页面而不是实际内容。还有一些人两次调用页面是不可接受的

http://www.codeproject.com/KB/aspnet/asproxy.aspx

http://www.codeproject.com/KB/aspnet/asproxy.aspx

http://www.johnchapman.name/aspnet-proxy-page-cross-domain-requests-from-ajax-and-javascript/

http://www.johnchapman.name/aspnet-proxy-page-cross-domain-requests-from-ajax-and-javascript/

Re-Render the page

重新渲染页面

I did not go this far but there are jscript engines out there that will look at the source and re-render the page based on the source file . but it would require hacking those jscripts.. and thats not an ideal situation for commercial entities... and some invole pure java applets or server side rendering

我没有走那么远,但是有 jscript 引擎会查看源代码并根据源文件重新呈现页面。但它需要破解那些 jscripts ......这对于商业实体来说不是一个理想的情况......还有一些涉及纯 Java 小程序或服务器端渲染

http://en.wikipedia.org/wiki/Server-side_JavaScript

http://en.wikipedia.org/wiki/Server-side_JavaScript

http://htmlunit.sourceforge.net/<-java not jscript

http://htmlunit.sourceforge.net/<-java 不是 jscript

http://maxq.tigris.org/

http://maxq.tigris.org/



EDIT 09-2013 UPDATE

编辑 09-2013 更新

All this can do done with HTML5 sockets. But easyXDM is great fallback for non HTML5 complaint pages.

所有这些都可以通过 HTML5 套接字完成。但对于非 HTML5 投诉页面,easyXDM 是很好的后备方案。

Solution 1Very Great Solution!

解决方案 1非常好的解决方案!

Using easyXDM

使用easyXDM

On your server you set up a page in the form of

在您的服务器上,您以以下形式设置页面

<html>
<head>
<script src="scripts/easyXDM.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">

    var transport = new easyXDM.Socket(/** The configuration */{
    remote: "http://www.OTHERDOMAIN.com/resize_intermediate.html?url=testpages/resized_iframe_1.html",

    //ID of the element to attach the inline frame to
    container: "embedded",
    onMessage: function (message, origin) {
        var settings = message.split(",");
        //Use jquery on a masterpage.
        //$('iframe').height(settings[0]);
        //$('iframe').width(settings[1]);

        //The normal solution without jquery if not using any complex pages (default)
        this.container.getElementsByTagName("iframe")[0].style.height = settings[0];
        this.container.getElementsByTagName("iframe")[0].style.width = settings[1];
    }
});

</script>

</head>

<body>
    <div id="embedded"></div>
</body>

and on the callers domain they just need to add the intermiedate_frame html and easyXDM.js in the same place. Like a parent folder - then you can access relative directories or a contained folder just for you.

在调用者域上,他们只需要在同一个地方添加 intermediate_frame html 和 easyXDM.js。就像父文件夹一样 - 然后您可以访问相关目录或只为您包含的文件夹。

OPTION 1

选项1

If you don't want to add scripts to all pages look at option 2!

如果您不想向所有页面添加脚本,请查看选项 2!

Then they can just add a simple jscript to the end of each the pages you need the resize to occur. No need to include the easyxdm in each of these pages.

然后他们可以在需要调整大小的每个页面的末尾添加一个简单的 jscript。无需在每个页面中都包含 easyxdm。

 <script type="text/javascript">
            window.onload = function(){ parent.socket.postMessage( (parseInt(document.body.clientHeight)) + "," + ( document.body.clientWidth ) );  };
        </script>

I have modified the parameters it sends. If you want the width to work properly then the pages on the otherdomain need to include the width of the page in a style somwhere that look something similar to:

我修改了它发送的参数。如果您希望宽度正常工作,则 otherdomain 上的页面需要在样式中包含页面的宽度,该样式看起来类似于:

<style type="text/css">
            html, body {
                overflow: hidden;
                margin: 0px;
                padding: 0px;
                background-color: rgb(75,0,85);
                color:white;
                width:660px
            }
            a {
            color:white;
            visited:white;
            }
        </style>

This works great for me. If the width is not included then the frame behaves a bit strange and kind'of tries to guess what it should be .. and will not shrink down if you need it to.

这对我很有用。如果不包括宽度,那么框架的行为会有点奇怪,并且有点试图猜测它应该是什么......并且如果你需要它不会缩小。

OPTION 2

选项 2

Modify the intermediate frame to poll for changes

修改中间帧以轮询更改

Your intermediate frame should look something like this..

你的中间框架应该看起来像这样..

    <!doctype html>
<html>
    <head>

        <title>Frame</title>
        <script type="text/javascript" src="easyXDM.js">
        </script>
        <script type="text/javascript">
            var iframe;
            var socket = new easyXDM.Socket({
                //This is a fallback- not needed in many cases
                swf: "easyxdm.swf",
                onReady: function(){
                    iframe = document.createElement("iframe");
                    iframe.frameBorder = 0;
                    document.body.appendChild(iframe);
                    iframe.src = "THE HOST FRAME";
            iframe.onchange = messageBack();

                },
                onMessage: function(url, origin){
                    iframe.src = url;
                }
            });

            //Probe child.frame for dimensions.
            function messageBack(){
                socket.postMessage ( iframe.contentDocument.body.clientHeight + "," + iframe.contentDocument.body.clientWidth); 
            };

            //Poll for changes on children every 500ms.
            setInterval("messageBack()",500); 

        </script>
        <style type="text/css">
            html, body {
                overflow: hidden;
                margin: 0px;
                padding: 0px;
                width: 100%;
                height: 100%;
            }

            iframe {
                width: 100%;
                height: 100%;
                border: 0px;
            }
        </style>
    </head>
    <body>

    </body>
</html>

The interval could be made more efficient to chaeck if size has change and only send if the dimensions changes isntead of posting messaging every 500ms. If you implement this check then you can change the polling as low as 50ms! have fun

如果大小发生变化,则可以更有效地检查间隔,并且仅在尺寸发生变化时才发送,而不是每 500 毫秒发送一次消息。如果您实施此检查,那么您可以将轮询更改为低至 50 毫秒!玩得开心



Work across browsers and is fast. Great debugging features !!

跨浏览器工作并且速度很快。强大的调试功能!!

Excellent Work to  Sean Kinsey  who made the script!!!


Solution 2(Works but not great)

解决方案 2(有效但不是很好)

So basically if you have a mutual agreement with the other domain then you can add a library to handle sendmessage. If you do not have any access the the other domain.. Keep on looking for more hacks- because I could not find or fully justify these I found.

所以基本上,如果您与其他域有相互协议,那么您可以添加一个库来处理 sendmessage。如果您没有任何访问其他域的权限.. 继续寻找更多黑客 - 因为我找不到或完全证明我发现的这些。

So the other domain will include these in there Head tag

所以另一个域将在那里包含这些 Head 标签

<script src="scripts/jquery-1.5.2.min.js" type="text/javascript"></script>
<script src="scripts/jquery.postmessage.min.js" type="text/javascript"></script>
<script src="scripts/club.js" type="text/javascript"></script>

In the club.js is just some custom calls i made for resize calls and contains..

在 club.js 中只是我为调整大小调用所做的一些自定义调用,并且包含..

 $(document).ready(function () {   
    var parent_url = decodeURIComponent( document.location.hash.replace( /^#/, '' ) ),link;
//Add source url hash to each url to authorise callback when navigating inside the frame.Without this clicking any links will break the communication and no messages will be received
$('a[href]').each(function(){ 
     this.href = this.href + document.location.hash ;
});
//Get the dimensions and send back to calling page.
var h1 = document.body.scrollHeight;
var w1 = document.body.scrollWidth;
$.postMessage({ if_height: h1, if_width: w1 }, parent_url, parent );
  });

And your page will do all the hard work and has a nice script...

您的页面将完成所有艰苦的工作,并有一个不错的脚本...

  //This is almost like request.querystring used to get the iframe data
  function querySt(param, e) {
         gy = e.split("&");
         for (i = 0; i < gy.length; i++) {
             ft = gy[i].split("=");
             if (ft[0] == param) {
                 return ft[1];
             }
         }
     }


     $(function () {
         // Keep track of the iframe dimensions.
         var if_height;
         var if_width;
         // Pass the parent page URL into the Iframe in a meaningful way (this URL could be
         // passed via query string or hard coded into the child page, it depends on your needs).
         src = 'http://www.OTHERDOAMIN.co.uk/OTHERSTARTPAGE.htm' + '#' + encodeURIComponent(document.location.href),
         // Append the Iframe into the DOM.
         iframe = $('<iframe " src="' + src + '" width="100%" height="100%" scrolling="no" frameborder="0"><\/iframe>').appendTo('#iframe');

         // Setup a callback to handle the dispatched MessageEvent event. In cases where
         // window.postMessage is supported, the passed event will have .data, .origin and
         // .source properties. Otherwise, this will only have the .data property.
         $.receiveMessage(function (e) {
             // Get the height from the passsed data.
             //var h = Number(e.data.replace(/.*if_height=(\d+)(?:&|$)/, ''));
             var h = querySt("if_height", e.data);
             var w = querySt("if_width", e.data);


             if (!isNaN(h) && h > 0 && h !== if_height) {
                 // Height has changed, update the iframe.
                 iframe.height(if_height = h);
             }
             if (!isNaN(w) && w > 0 && w !== if_width) {
                 // Height has changed, update the iframe.
                 iframe.width(if_width = w);
             }
             //For debugging only really- can remove the next line if you want
             $('body').prepend("Recieved" + h + "hX" + w + "w .. ");
             // An optional origin URL (Ignored where window.postMessage is unsupported).
           //Here you must put the other domain.com name only! This is like an authentication to prevent spoofing and xss attacks! 
         }, 'http://www.OTHERDOMAIN.co.uk');
     });


OPTION 3

选项 3

Their is now a small JS library for managing resizing cross-domain iFrames, it still requires the iFrame to have a bit of JavaScript in it, however, this is just 2.8k (765 bytes Gzipped) of native JS that does not have any dependancies and it doesn't do anything until called by the parent page. This means it's a nice guest on other people systems.

他们现在是一个用于管理跨域 iFrame 大小调整的小型 JS 库,它仍然需要 iFrame 中包含一些 JavaScript,但是,这只是 2.8k(765 字节 Gzipped)的原生 JS,没有任何依赖项在被父页面调用之前它不会做任何事情。这意味着它是其他人系统上的好客。

This code uses mutationObserver to detect DOM changes and also looks out for resize events, so that the iFrame remains sized to the content. Works in IE8+.

此代码使用 mutationObserver 来检测 DOM 更改并查看调整大小事件,以便 iFrame 保持与内容一致的大小。适用于 IE8+。

https://github.com/davidjbradshaw/iframe-resizer

https://github.com/davidjbradshaw/iframe-resizer

采纳答案by Sean Kinsey

The thing is - there is no other way than using Cross-Domain Messaging for this since you need to get the computed height from a document in one domain, to a document in a different domain.

问题是 - 除了使用跨域消息传递之外别无他法,因为您需要将计算高度从一个域中的文档获取到不同域中的文档。

So, either you do this using postMessage(works in all moder browsers), or you spend 5 minutes adapting the resize iframe examplefrom easyXDM.

因此,要么使用postMessage(适用于所有现代浏览器)执行此操作,要么花费 5 分钟调整来自 easyXDM的调整大小 iframe 示例

The other party really just needs to copy a few files onto their domain, and add a single line of code to their document..

对方真的只需要将几个文件复制到他们的域中,并在他们的文档中添加一行代码即可。

回答by Baker Humadi

Similar to what Sean has mentioned, you can use postMessage. I've spent so much time trying different ways to resize iframe with cross-domain but no luck until I stumbled on this great blog post by David Walsh: http://davidwalsh.name/window-iframe

与 Sean 提到的类似,您可以使用 postMessage。我花了很多时间尝试不同的方法来跨域调整 iframe 的大小,但没有运气,直到我偶然发现了 David Walsh 的这篇很棒的博客文章:http: //davidwalsh.name/window-iframe

This is a combination of my code and David's solution. My solution is geared specifically toward resizing iframes.

这是我的代码和大卫的解决方案的组合。我的解决方案专门针对调整 iframe 的大小。

In the child page, find the height of the page and pass it to the parent page (which contains the iframe). Replace element_id with your element id (html, body, whatever).

在子页面中,找到页面的高度并将其传递给父页面(其中包含 iframe)。将 element_id 替换为您的元素 id(html、body 等)。

<script>
function adjust_iframe_height(){
    var actual_height = document.getElementById('element_id).scrollHeight;
    parent.postMessage(actual_height,"*"); 
    //* allows this to post to any parent iframe regardless of domain
}
</script>

<body onload="adjust_iframe_height();"> 
//call the function above after the content of the child loads

On the parent window, add this code. Replace iframe_id with your iframe ID:

在父窗口上,添加此代码。将 iframe_id 替换为您的 iframe ID:

<script>
// Create IE + others compatible event handler
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen to message from child window
eventer(messageEvent,function(e) {
  console.log('parent received message!:  ',e.data);
  document.getElementById('iframe_id').height = e.data + 'px';
},false);
</script>

If you open the console, you will see the height being printed in the console log. This will help you in debugging which is why I left it there.

如果您打开控制台,您将看到控制台日志中打印的高度。这将帮助您进行调试,这就是我将它留在那里的原因。

Best, Baker

最好的,贝克

回答by David Bradshaw

Having looked a lots of different solution to this I ended up writing a simple small library to take a account of a number of different use cases. As I needed a solution that supported multiple user generated iFrames on a portal page, supported browser resizes and could cope with the host page JavaScript loading after the iFrame. I also add support for sizing to width and a callback function and allow the override of the body.margin, as you will likely want to have this set to zero.

在查看了很多不同的解决方案之后,我最终编写了一个简单的小型库来考虑许多不同的用例。因为我需要一个解决方案,在门户页面上支持多个用户生成的 iFrame,支持浏览器调整大小,并且可以处理 iFrame 之后的主机页面 JavaScript 加载。我还添加了对调整宽度和回调函数的支持,并允许覆盖 body.margin,因为您可能希望将此设置为零。

https://github.com/davidjbradshaw/iframe-resizer

https://github.com/davidjbradshaw/iframe-resizer

The iframe code is just a little self-contained JavaScript, so that it's a good guest on other people pages.

iframe 代码只是一些独立的 JavaScript,因此它是其他人页面上的好客。

The script is then initialised on the host page with the following available options.

然后使用以下可用选项在主机页面上初始化脚本。

iFrameResize({
    log                    : true,  // For development
    autoResize             : true,  // Trigering resize on events in iFrame
    contentWindowBodyMargin: 8,     // Set the default browser body margin style (in px)
    doHeight               : true,  // Calculates dynamic height
    doWidth                : false, // Calculates dynamic width
    enablePublicMethods    : true,  // Enable methods within iframe hosted page 
    interval               : 32,    // interval in ms to recalculate body height, 0 to disable refreshing
    scrolling              : false, // Enable the scrollbars in the iFrame
    callback               : function(messageData){ // Callback fn when message is received
        $('p#callback').html(
            '<b>Frame ID:</b> '    + messageData.iframe.id +
            ' <b>Height:</b> '     + messageData.height +
            ' <b>Width:</b> '      + messageData.width + 
            ' <b>Event type:</b> ' + messageData.type
        );
    }
});

回答by Kanstantsin Kamkou

Nowadays there is only 4 solutions I know:

现在我只知道4种解决方案:

Only the third one can resolve many problems. For example you can create responsive iFrame; close it from inside or you can communicate with it. But to do that you need iFrame in Iframe and the "third party cookies" workaround (optional).

只有第三个才能解决很多问题。例如,您可以创建响应式 iFrame;从内部关闭它,或者您可以与它通信。但要做到这一点,您需要 Iframe 中的 iFrame 和“第三方 cookie”解决方法(可选)。

I've created an article about it with example: Event-driven cross-domain iFrame

我已经用示例创建了一篇关于它的文章:事件驱动的跨域 iFrame

回答by sparkholiday

Have you looked into the 'object-fit' HTML5 attributes? Scales video/images to the iframe, rather than scaling the iframe (nice if you grab a medium-sized image that ends up being 5,000px in width). The "fit" option (others are "cover" and "fill") uses a sort-of-letterbox approach to fit the source in while preserving the aspect ratios. For viewing by the HTML5-less out there, it looks like there a whoooole lot of polyfills available. This one is great, but a bug on Edge's end has kept it incompatible with Microsoft's New Nightmare for about a year, now: https://github.com/anselmh/object-fit

您是否研究过“object-fit”HTML5 属性?将视频/图像缩放到 iframe,而不是缩放 iframe(如果您抓取最终宽度为 5,000 像素的中等大小的图像,那就太好了)。“适合”选项(其他是“封面”和“填充”)使用一种类似信箱的方法来适应源,同时保留纵横比。对于没有 HTML5 的人进行查看,看起来有很多可用的 polyfill。这个很棒,但是 Edge 端的一个错误使它与微软的 New Nightmare 不兼容大约一年了,现在:https: //github.com/anselmh/object-fit

EDIT: To get around cross domain issues, you can always just do the work in a Chrome Extension Content Script, since it thinks it's part of the page you're sticking your iframe on.

编辑:为了解决跨域问题,您总是可以在 Chrome 扩展内容脚本中完成工作,因为它认为它是您粘贴 iframe 的页面的一部分。

回答by Limitless isa

HTTPS another link get height to iframe autoheight

HTTPS 另一个链接获取 iframe 自动高度的高度

https://-a.comcontent:

https://-a.com内容:

 <!DOCTYPE html>
    <html>
    <head>
        <title>Test Page</title>
    </head>
    <body>
        Test Page:
        <hr/>
        <iframe id="iframe" src="https://-b.com" style="width:100%;min-height:600px;border:none;" scrolling="no" ></iframe>
        <script>
        // browser compatibility: get method for event 
        // addEventListener(FF, Webkit, Opera, IE9+) and attachEvent(IE5-8)
        var myEventMethod = 
            window.addEventListener ? "addEventListener" : "attachEvent";
        // create event listener
        var myEventListener = window[myEventMethod];
        // browser compatibility: attach event uses onmessage
        var myEventMessage = 
            myEventMethod == "attachEvent" ? "onmessage" : "message";
        // register callback function on incoming message
        myEventListener(myEventMessage, function (e) {
            // we will get a string (better browser support) and validate
            // if it is an int - set the height of the iframe #my-iframe-id
            if (e.data === parseInt(e.data)) 
                document.getElementById('iframe').height = e.data + "px";
        }, false);
        </script>
    </body>
    </html>


https://-b.comiframe content:

https://-b.comiframe 内容:

<!DOCTYPE html>
<html>
<head>
    <title>Test Iframe Content</title>
    <script type="text/javascript">
    // all content including images has been loaded
    window.onload = function() {
        // post our message to the parent
        window.parent.postMessage(
            // get height of the content
            document.body.scrollHeight
            // set target domain
            ,"*"
        )
    };
</script>
</head>
<body>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>1
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>2
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>3
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>4
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>5
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>6
</body>
</html>


Work Table:

工作表:

xcom http > ycom https WORK

xcom http > ycom https 工作

xcom https > ycom https WORK

xcom https > ycom https 工作

xcom http > ycom http WORK

xcom http > ycom http 工作

xcom https > ycom http WORK

xcom https > ycom http 工作

Test Work Screenshot

测试工作截图

回答by Elton Morais

Instead of use scroll=no on the iframe, I change it to "auto". Then, I get the size of the actual window

我没有在 iframe 上使用 scroll=no,而是将其更改为“自动”。然后,我得到实际窗口的大小

$(window).height();

and use that as the iframe height attribute.

并将其用作 iframe 高度属性。

Well, the result is...

嗯,结果是……

We will never have the "page" scroll, only the "iframe" scroll. When You navigate, doesn't matter who is the scroll, but the important is that there's only 1.

我们永远不会有“页面”滚动,只有“iframe”滚动。当你导航时,谁是卷轴并不重要,但重要的是只有 1 个。

Well, there's the problem of the user simply resize the window while he's navigating. To solve that, I use:

嗯,存在的问题是用户在导航时只需调整窗口大小。为了解决这个问题,我使用:

setInterval(getDocHeight, 1);

Did You think that that solution will cause any bugs? It's working for me, and on the iFrame I had dynamic contect generated by php. I'm afraid of future bugs with that...

您是否认为该解决方案会导致任何错误?它对我有用,在 iFrame 上我有由 php 生成的动态内容。我害怕未来的错误......

回答by anothershrubery

Are you looking to find the height of the page contained within the iframe? I got some javascript working which checks the height of the iframe content then sets the iframe's height to the height of the content.

您是否要查找 iframe 中包含的页面高度?我使用了一些 javascript 来检查 iframe 内容的高度,然后将 iframe 的高度设置为内容的高度。

var Height = document.getElementById('iFrameId').contentWindow.document.body.scrollHeight;

document.getElementById('iFrameId').height = Height;

However, this only works if the page you are showing in the iframe is on the same domain. If it's not you cannot access the required information. Hence, the access denied error.

但是,这仅适用于您在 iframe 中显示的页面位于同一域中的情况。如果不是,您将无法访问所需的信息。因此,访问被拒绝错误。

回答by user2961151

To resize an iframe, here's a simple script:

要调整 iframe 的大小,这里有一个简单的脚本:

this goes in the head: (this was written for a php script, for html, change the ' to " and the \" to '...

这是在头脑中:(这是为 php 脚本编写的,对于 html,将 ' 更改为 " 并将 \" 更改为 '...

<script type='text/javascript'>
<!--
function resizeIframe(id){
/*
this.obj=obj
//this.obj.width=null
//this.obj.width=window.frames[\"sizeframe1\"].document.body.scrollWidth
this.obj.style.height=\"\" // for Firefox and Opera
setTimeout(\"this.obj.style.height=this.obj.contentWindow.document.body.scrollHeight+(notIE?heightOffset:0)\",10) // setTimeout required for Opera
*/

el=document.getElementById(id)
el.style.height='200px' // for Firefox and Opera
setTimeout('el.style.height=el.contentWindow.document.body.scrollHeight+\"px\"',1) // setTimeout required for Opera
}

// -->
</script>"

end of head

头尾

this goes in the body (remember, this was written for a php script, for html change all the ' to " and the \" to '...)

这在正文中(请记住,这是为 php 脚本编写的,对于 html,将所有 ' 更改为 " 并将 \" 更改为 '...)

<iframe onload='resizeIframe(this.id)' allowTransparency=\"true\" name='ccpaymentwindow' id='sizeframe1' marginwidth='1' marginheight='1' height='700' width='690' border='0' frameborder='1' scrolling='no' src='ccmslink.php?variable1=" . $variable1 . "'></iframe>

bonus: there's some hints above. As it is set for php scripting, you can do a lot with it...to learn more, do more...

奖励:上面有一些提示。因为它是为 php 脚本设置的,所以你可以用它做很多事情……要了解更多,做更多……

the key to this is "sizeframe1" .... for multiple "resizers" on the same page, copy the same script but change the id in iframe and the name in the script in the head, and viola! you have multiple resizers on the same page...it works very well!

关键是“sizeframe1”......对于同一页面上的多个“调整器”,复制相同的脚本但更改iframe中的id和头部脚本中的名称,中提琴!您在同一页面上有多个调整器……效果很好!

have phun.

有奔。