Javascript – > iframe使用postMessage方法resize

我试图了解另一个Stackoverflow答案( 跨域iframe调整器? ),旨在解决如何根据其高度调整iframe (托管在与其嵌入的域分开的域上)的大小。 想知道是否有人可以在下面回答我的问题。

解决方案:

IFRAME:

      

Got post?

Lots of stuff here which will be inside the iframe.

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

  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); }    

我的问题:

  1. http://target.domain.com是指iframe所在的域
    嵌入内,对吧? 不是托管iframe的域名?
  2. function resizeCrossDomainIframe(id, other_domain) { line,我不应该将“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的父文档

以下是我在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 } }