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

Javascript --> iframe resizing using postMessage method

本文关键字:方法 调整 postMessage 使用 gt iframe Javascript--      更新时间:2023-09-26

我正在尝试理解另一个Stackoverflow答案(跨域iframe resizer?),该答案旨在解决如何根据高度调整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中编写了等效的内容,它加载在嵌入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';s母文档

以下是我在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
  }
}
相关文章: