【问题标题】:JavaScript: Event listener on iFrame resize / height attribute change (FB comment box)JavaScript:iFrame 调整大小/高度属性更改的事件侦听器(FB 评论框)
【发布时间】:2011-10-31 13:44:45
【问题描述】:
我有以下问题:当iframe(Facebook 评论框)改变高度时,我需要为它添加一个事件监听器。
我无法访问或更改contentWindow,因为它是跨域的。但是必须有一个回调函数或者改变height属性的东西。
有没有办法在属性更改或其他东西上添加事件监听器?我已经尝试过 onResize 和 onChange。
我快疯了...有人有想法吗?
非常感谢!!
【问题讨论】:
标签:
facebook
iframe
facebook-javascript-sdk
【解决方案1】:
简短回答:不。
但是,您可以使用“postMessage”和“receiveMessage”从一个 iframe 发送到另一个跨域。 (当然,只有当您可以访问 iframed 内容时——我怀疑它不是在 facebook 上的。)
无论如何......为了将来的帮助......
(在 iframe 页面上)
var ii = {}
ii.window_height = 800;
var sendHeight = function () {
var window_height = $('body').outerHeight(true);
if (window_height != ii.window_height) {
ii.window_height = window_height;
window.parent.postMessage(ii.window_height, "http://containerDomain.com");
}
}
setInterval(sendHeight, 2000);
(在容器页面上)
function receiveMessage(evt) {
if (evt.origin === 'https://iframedDomain.com')
{
var iframe_content_height = evt.data;
$('#iframe_form').animate({height: iframe_content_height });
}
}
if ($.browser.msie) {
window.attachEvent('onmessage', receiveMessage);
} else {
window.addEventListener('message', receiveMessage, false);
}
记得更改每个脚本中的域。
注意:这是使用 jQuery - 它可以工作,但我确信有人能比我写得更好?也不太为检查高度的间隔感到骄傲……如果可以的话,可能会更新。