[英]Javascript --> iframe resizing using postMessage method
我试图了解另一个Stackoverflow答案( 跨域iframe调整程序? ),该答案旨在解决如何根据其高度调整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>
我的问题:
在function resizeCrossDomainIframe(id, other_domain) {
行中,我不应该将“ id”与iframe
的id
互换,而将“ other_domain”与iframe
所在的域名互换,对吗? 它们只是我稍后在调用函数时指定的参数。
我没有在iframe
标记中使用onload
,而是在jQuery中编写了等效的代码,该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
看起来合适吗?
我需要做类似的事情,发现这个例子看起来更简单: 使用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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.