【问题标题】:iframe resize height automatically not workingiframe自动调整高度不起作用
【发布时间】:2014-12-08 22:43:47
【问题描述】:

您好,我正在尝试根据 iframe 的内容调整 iframe 的大小,但它无法正常工作可能是因为跨域

这是我正在使用的代码

<script language="javascript" type="text/javascript">
  function resizeIframe(obj) {
    obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
  }
</script>
<iframe src="http://other_domain_name/get?v=07armilCx5A" frameborder="0" scrolling="no" id="iframe" width="100%" height="300px" onload="javascript:resizeIframe(this);"></iframe>

请帮助我如何解决这个问题以从其他域中获取 iframe 中的页面

【问题讨论】:

  • 检查resizeIframe函数中contentWindow的值。
  • 对于跨域消息传递,您可以使用 easyXDM
  • 您没有访问嵌入内容中的任何内容,我认为这里不可能存在跨域问题。
  • 但嵌入后无法正常工作,无法加载完整页面

标签: javascript jquery html css iframe


【解决方案1】:

您可以使用相同的域来避免跨域安全保护或使用postMessage。 这只有在您可以控制 iframe 内容时才有可能...

您可能需要根据您的上下文(iframe ID 等)调整此代码,但它为您提供了一个可行的解决方案:我在 homair.com 上使用它。当我在我的计算机上开发时,我遇到了跨域问题,这让我可以避免这种情况;)

别怕,仔细研究一下代码就很简单了!!

在父网站方面:

function adjustIframe(height) {
  if (!height) {
    try {
      height = jQuery("#your-iframe").contents().height();
    }
    catch (e) {
    }
  }

  jQuery("#iframe-wrapper").height(height);
}

function listenIframe() {
  // Here "addEventListener" is for standards-compliant web browsers and "attachEvent" is for IE Browsers.
  var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
  var eventer = window[eventMethod];

  // Now...
  // if "attachEvent", then we need to select "onmessage" as the event.
  // if "addEventListener", then we need to select "message" as the event

  var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

  // Listen to message from child IFrame window
  eventer(messageEvent, function (e) {
    if (e.origin == 'http://your_iframe_domain.com') {
      // Action asked from the JS in the iframe
      if (e.data.action == 'resizeWindow') {
        adjustIframe(e.data.height);
      }
    }
  }, false);
}

在 iframe 内容方面:

function adjustParentIframe() {
    // try to call the parent JS function, if the domain is the same
    try {
      setTimeout(parent.adjustIframe, 500);
    }
    // if not => exception catched
    catch (ex) {
      // Using window.parent.postMessage("data", targetOrigin);
      // Send a message to the parent window,
      // which listen to the events, coming from the iframe.
      window.parent.postMessage({
        // action to do on the parent side.
        action: 'resizeWindow',
        // Arguments to send : the height of this page (the iframe content !)
        height: ($(document).height() + 10)
      }, "*");
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 2014-04-25
    • 1970-01-01
    相关资源
    最近更新 更多