JavaScript: iFrame调整大小/高度属性的事件监听器(FB评论框)



我有以下问题:我需要为iframe (Facebook评论框)添加一个事件侦听器,当它改变其高度时。

我不能访问或更改contentWindow,因为它是跨域的。但是必须有一个回调函数或一些东西来改变height属性。

是否有一种方法可以在属性更改或其他东西上添加事件侦听器?我已经试过onResize和onChange了。

我要疯了…有人知道吗?

非常感谢!!

简短回答:No.

然而,你可以使用"postMessage"one_answers"receiveMessage"从一个iframe发送到另一个跨域。(当然,只有当你可以访问框架内容时-我怀疑不是因为它在facebook上。)

无论如何……为将来的帮助....

(在框架页上)

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 -它的工作原理,但我相信有人能写得比我更好?也不要太骄傲的间隔检查高度…如果可以的话我可能会更新

最新更新