【问题标题】:Iframe resize is not working in cross domain in javascriptiframe调整大小在javascript中的跨域中不起作用
【发布时间】:2014-04-17 14:17:33
【问题描述】:

我正在使用此脚本根据内容自动调整 iframe 的高度和宽度..

<script language="JavaScript">


function autoResize(id){
    var newheight;
    var newwidth;

    if(document.getElementById){
        newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
        newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
    }

    document.getElementById(id).height= (newheight) + "px";
    document.getElementById(id).width= (newwidth) + "px";
}
</script>

此脚本不能在跨域服务器中运行..有其他方法吗?

【问题讨论】:

  • 如果你控制了两个域的内容。

标签: javascript jquery iframe cross-domain


【解决方案1】:

我自己最近也遇到了这个问题。 最后我用 postMessage 方法解决了。

  1. 在 iFrame 包含的文档中,我检查它是否实际上是从 iFrame 运行的。

    function inIframe(){
        if(top != self){
             var contentHeight = $('#myIframeContent').height(); //Just this part I did with jQuery as I was sure that the document uses it
             postSize(contentHeight);
             }
        }
    
  2. 如果文档在 iFrame 中运行,请调用我们将调用 postSize 的函数。

    function postSize(height){
         var target = parent.postMessage ? parent : (parent.document.postMessage ? parent.document : undefined);
    
        if(typeof target != "undefined" && document.body.scrollHeight){
            target.postMessage(height, "*");
            }
        }
    
  3. 将以下代码添加到包含您的 iFrame 的文档中

    function receiveSize(e){
        if(e.origin === "http://www.mywebsite.net"){
            var newHeight = e.data + 35;
            document.getElementById("myIframeID").style.height = newHeight + "px";
            }
        }
    
    window.addEventListener("message", receiveSize, false);
    

不幸的是,我不记得这一切的确切来源,因为我在 Stackoverflow 上查看了许多不同的解决方案,但也查看了不同的网站。但是这个解决方案对我很有效。

以前有人遇到过这个问题,我在这里发布了这个解决方案。这对他来说似乎也很好用: Error: Permission denied to access property 'document'

干杯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-20
    • 2011-08-02
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    • 2011-11-23
    • 2011-04-26
    相关资源
    最近更新 更多