8

"Error: Permission denied to access property 'document'"当我已经在我的定义中X-FRAME options允许其他域时,我不断收到错误,就像这样..

 <?php
        header('X-Frame-Options: ALLOW-FROM http://mydomain.com'); 
    ?>

下面是 iframe 请求的标头,清楚地表明我已定义允许域访问 iframe 但不工作。我想要的只是使用 javascript 调整 iframe 的大小。

在此处输入图像描述

这是我调整 iframe 高度大小的 javascript 代码。

<iframe src="http://mydomain.com/xxx/yyy" id="idIframe" onload="iframeLoaded();" allowtransparency="true" frameborder="0" width="100%" scrolling="no"></iframe>
<script type="text/javascript">
function iframeLoaded() {
    var iFrameID = document.getElementById('idIframe');
    if(iFrameID) {
          iFrameID.height = "";
          if(iFrameID.contentWindow.document.body.scrollHeight < 500) {
              iFrameID.height = "500px";
          } else {
              iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
          }
    }   
}
</script>

我怎样才能做到这一点?请建议。

4

3 回答 3

20

我最近自己也遇到了这个问题。最后我用 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 上查看了许多不同的解决方案,但也查看了不同的网站。但是这个解决方案对我很有用。

干杯

于 2014-03-18T14:12:19.200 回答
1

不知道为什么其他解决方案使用 iFrame ID。它也应该在没有:

iFrame 内向外部发送消息的页面:

<script>
     parent.postMessage('your message', '*');
</script>

父框架:

window.addEventListener("message", receiveMessage, false);

function receiveMessage(event)
{
  console.log('Message: ',  event.data);
}
于 2018-10-15T12:49:01.253 回答
-4

将 compatability.js 更新到最新版本为我修复了它。

于 2016-03-10T20:58:01.640 回答