跨域iframe通信

Chr*_*ris 15 javascript iframe cross-domain

我在页面上创建了一个iframe,并且页面的域名被明确设置为"xyz.com",但iframe的域名默认为"dev.xyz.com",这是我正在开发的实际域名.

问题是,当我尝试通过iframe.contentWindow.document访问iframe时,由于域的不同而失败.

我已经尝试将iframe的src设置为一个带有document.domain ='xyz.com'的文件,但这似乎没有做到这一点......

有任何想法吗?

NVI*_*NVI 12

iframe中的页面:

<script>
document.domain = document.domain;
</script>
Run Code Online (Sandbox Code Playgroud)

它看起来很傻,但它确实有效.请参阅" document.domain = document.domain做什么? ".


Sui*_*oth 8

经过一些研究,我发现这个jQuery插件使得postMessage使用各种技巧向后兼容旧版浏览器.

这是一个快速示例,显示如何将iframe的主体高度发送到父窗口:

在主持人(父)页面上:

    // executes when a message is received from the iframe, to adjust 
    // the iframe's height
    $.receiveMessage(
        function( event ){
            $( 'my_iframe' ).css({
                height: event.data
            });
    });
   // Please note this function could also verify event.origin and other security-related checks.
Run Code Online (Sandbox Code Playgroud)

在iframe页面上:

$(function(){

    // Sends a message to the parent window to tell it the height of the 
    // iframe's body        
    var target = parent.postMessage ? parent : (parent.document.postMessage ? parent.document : undefined);

    $.postMessage(
        $('body').outerHeight( true ) + 'px',
        '*',
        target
    );

});
Run Code Online (Sandbox Code Playgroud)

我在XP和W7上的Chrome 13 +,Firefox 3.6 +,IE7,8和9上进行了测试,在OSX和W7上进行了测试.;)