【问题标题】:Error: Permission denied to access property 'document'错误:访问属性“文档”的权限被拒绝
【发布时间】:2014-04-24 06:00:42
【问题描述】:

我不断收到错误"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>

我该怎么做?请提出建议。

【问题讨论】:

  • X-Frame-Options 确定是否允许在框架内显示页面。它不授予跨域 JS 权限。

标签: javascript php jquery x-frame-options


【解决方案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 上查看了许多不同的解决方案,但也查看了不同的网站。但是这个解决方案对我很有效。

干杯

【讨论】:

    【解决方案2】:

    不确定为什么其他解决方案使用 iFrame ID。它也应该在没有以下情况下工作:

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

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

    父框架:

    window.addEventListener("message", receiveMessage, false);
    
    function receiveMessage(event)
    {
      console.log('Message: ',  event.data);
    }
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 请说明您使用的版本、更新到的内容以及您当时使用的其他软件。
      猜你喜欢
      • 1970-01-01
      • 2014-06-23
      • 2015-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多