我想了解另一個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>
我的問題:
- http://target.domain.com指的是iframe內嵌的域名是
,對嗎?不是iframe託管的域名? 在
function resizeCrossDomainIframe(id, other_domain) {
一行中,我不應該將iframe
的「id
」和帶有iframe託管的域名的「other_domain」與「id」互換,對吧?它們只是我在稍後調用函數時指定的參數。取而代之的是
iframe
標籤內使用onload
的,我寫了jQuery的等價物,它加載的頁面上嵌入的iframe:$('#petition-embed').load(function() { resizeCrossDomainIframe('petition-embed','http://target.domain.com'); });
我加各地返程括號:
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
確實那看起來正確?