Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-Domain iframe communication

I have an iframe being created on a page, and the page's domain is being explicitly set to 'xyz.com' but the iframe's domain is defaulting to 'dev.xyz.com', which is the actual domain i'm developing for.

The problem is, when I try to access that iframe via iframe.contentWindow.document, it fails due to the difference in domain.

I've tried setting the iframe's src to a file with document.domain = 'xyz.com' but that doesn't seem to be doing the trick...

Any ideas?

like image 747
Chris Avatar asked Dec 22 '09 22:12

Chris


2 Answers

Page inside iframe:

<script>
document.domain = document.domain;
</script>

It looks silly, but it works. See "What does document.domain = document.domain do?".

like image 160
NVI Avatar answered Sep 16 '22 11:09

NVI


After some research, I found this jQuery plugin that makes postMessage backwards-compatible with older browsers using various tricks.

Here is a quick example showing how to send the height of the iframe's body to the parent window:

On the host (parent) page:

    // 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.

On the iframe page:

$(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
    );

});

I've tested this on Chrome 13+, Firefox 3.6+, IE7, 8 and 9 on XP and W7, safari on OSX and W7. ;)

like image 34
0x6A75616E Avatar answered Sep 16 '22 11:09

0x6A75616E