我想了解另一个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
确实那看起来正确?