2013-07-23 49 views
1

我想了解另一個Stackoverflow的答案(cross-domain iframe resizer?),旨在解決如何根據其高度來調整iframe(託管在與其所嵌入的域不同的域上)的大小。想知道是否有人可以回答我的問題。Javascript - > iframe調整使用postMessage方法

解決方案:

的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) {一行中,我不應該將iframe的「id」和帶有iframe託管的域名的「other_domain」與「id」互換,對吧?它們只是我在稍後調用函數時指定的參數。

  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

確實那看起來正確?

回答

2

我需要做同樣的事情,發現這個例子似乎更簡單:using postmessage to refresh iframe's parent document

這裏是我結束了在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 
    } 
}