繁体   English   中英

Javascript->使用postMessage方法调整iframe的大小

[英]Javascript --> iframe resizing using postMessage method

我试图了解另一个Stackoverflow答案( 跨域iframe调整程序? ),该答案旨在解决如何根据其高度调整iframe (位于与嵌入其的域不同的域中)的大小。 想知道是否有人可以在下面回答我的问题。

解决方案:

IFRAME:

 <!DOCTYPE html>
<head>
</head>
<body onload="parent.postMessage(document.body.scrollHeight, 'http://target.domain.com');">
  <h3>Got post?</h3>
  <p>Lots of stuff here which will be inside the iframe.</p>
</body>
</html>

包含iframe的父页面(并想知道其高度):

<script type="text/javascript">
   function resizeCrossDomainIframe(id, other_domain) {
    var iframe = document.getElementById(id);
    window.addEventListener('message', function(event) {
      if (event.origin !== other_domain) return; // only accept messages from the specified domain
      if (isNaN(event.data)) return; // only accept something which can be parsed as a number
      var height = parseInt(event.data) + 32; // add some extra height to avoid scrollbar
      iframe.height = height + "px";
    }, false);
  }
</script>

<iframe src='http://example.com/page_containing_iframe.html' id="my_iframe"     onload="resizeCrossDomainIframe('my_iframe', 'http://example.com');">
</iframe>

我的问题:

  1. http://target.domain.com是指iframe所在的域
    嵌入其中吧? 不是iframe托管的域?
  2. function resizeCrossDomainIframe(id, other_domain) {行中,我不应该将“ id”与iframeid互换,而将“ other_domain”与iframe所在的域名互换,对吗? 它们只是我稍后在调用函数时指定的参数。

  3. 我没有在iframe标记中使用onload ,而是在jQuery中编写了等效的代码,该jQuery在嵌入iframe的页面上进行加载:

    $('#petition-embed').load(function() { resizeCrossDomainIframe('petition-embed','http://target.domain.com'); });

  4. 我在返回周围添加了括号:

    if (event.origin !== other_domain) {return;} // only accept messages from the specified domain if (isNaN(event.data)) {return;} // only accept something which can be parsed as a number

看起来合适吗?

我需要做类似的事情,发现这个例子看起来更简单: 使用postmessage刷新iframe的父文档

这是我在iframe中最终得到的结果:

window.onload = function() {
  window.parent.postMessage(document.body.scrollHeight, 'http://targetdomain.com');
}

并在接收方父母中:

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

function receiveMessage(evt){
  if (evt.origin === 'http://sendingdomain.com') {
    console.log("got message: "+evt.data);
    //Set the height on your iframe here
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM