【问题标题】:Cross domain but control both domains: Set the height of an iframe per it's contents?跨域但控制两个域:根据内容设置 iframe 的高度?
【发布时间】:2013-06-29 01:11:38
【问题描述】:

我们有两个域,domain.comsub.domain.com

在 domain.com 上

<html> 
<head> 
    <title>Main</title> 
</head> 
<body>
    <h1>This is the parent</h2>
    <iframe src="http://sub.domain.com/results.aspx" 
            width="100%" height="1px" id="iframe1">
    </iframe>
</body>
</html>

问题:我们如何将 iframe 高度从 1px 调整到它的真实高度(当 iframe 加载时)?当用户在 iframe 中播放时,它的高度可能会发生变化,所以我怀疑可能需要将它与某些事件挂钩。

现在我完全意识到在浏览器中阻止了跨脚本,甚至子域(或不同的端口号)也构成了“跨域”。但是,我们控制这两个域,所以我正在为此寻找一个好的解决方案。我们查看了window.postMessage,它似乎是专门为此设计的,但无法使其发挥作用。

【问题讨论】:

标签: javascript jquery iframe cross-domain


【解决方案1】:

您的案例很简单,因为它是跨脚本子域(而不是跨脚本不同域)。只需在您的页面和 iframe 中分配 document.domain = "domain.com"。 欲了解更多信息,请查看: Cross sub domain iframes and JavaScriptHow to communicate between frames?

【讨论】:

    【解决方案2】:

    您正在寻找的是 iframe 消息传递:

    https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage

    在父页面中:

    var iframe = document.getElementById('myIframe');
    
    function resizeIframe(event){
      if (event.origin !== "http://example.org"){
        // We trust this message
        iframe.setAttribute("style", "width:" + event.data + "px;");
      }
    }
    
    window.addEventListener('message', resizeIframe, false);
    

    在子页面中:

    function postParent(){
      window.postMessage($(body).height(), 'http://parentdomain.org');
    }
    
    $(window).on('load', postParent);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-02
      • 2013-02-04
      • 2016-01-12
      • 1970-01-01
      • 2011-07-04
      • 2013-11-22
      • 2016-04-03
      • 1970-01-01
      相关资源
      最近更新 更多