我遇到以下问题:我需要在更改高度时为iframe
(Facebook评论框)添加一个事件监听器。
我无法访问或更改contentWindow
,因为它是跨域的。但必须有一个回调函数或改变height
属性的东西。
有没有办法在属性更改或事物上添加事件监听器?我已经尝试过onResize和onChange。
我对此感到疯狂......任何人有想法?
非常感谢!!
答案 0 :(得分:0)
简短回答:不。
但是,您可以使用“postMessage”和“receiveMessage”从一个iframe发送到另一个跨域。 (当然,只有你可以访问iframed内容 - 我怀疑不是因为它在facebook上。)
无论如何......为了将来的帮助......
(在iframed页面上)
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 - 它可以工作,但我相信有人可以写得比我好吗?对于检查高度的间隔也不会太自豪...如果可以,可能会更新。