How to share jQuery .data() data through iframe's?

4.3k views Asked by At

I'm trying to share jQuery data from one or more iframe'd html pages with their parent html document. What I need is an inter-iframe communication and if possible (highly desireble) to share/exchange .data() i.e. the $.cache of both jQuery objects (in the parent and child iframe).

Someting similar to this:

Parent html:

<!DOCTYPE html>
<html>
    <head>

        <title >iframe-data</title>

        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" ></script>


        <script type="text/javascript" >

            jQuery(function($){
                var testData = 'hello world from #div1';
                $('#div1').data('test',testData);
                var newTestData = $('.div2').closest('.div1').data('test');
                $('#div2').append( 'Parent window: "' + testData + '" === "' + newTestData + '" => ' + (testData === newTestData) );
            }); // jQuery()

        </script>
    </head>
    <body>

        <div id="div1" class="div1" >
            <div id="div2" class="div2" >
            </div>
            <iframe src="iframe-data2.html" ></iframe>
        </div>

    </body>
</html>

Iframe html:

<!DOCTYPE html>
<html>
    <head>

        <title >iframe-data2</title>

        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" ></script>


        <script type="text/javascript" >

            jQuery(function($){
                var testData = 'hello world from #div1';
                var $body = $(window.top.document.body);
                var $div1 = $body.find('#div1');
                var outsideTestData = $body.find('#div1').data('test');
                var $div2 = $('#div2');
                $div2.append( 'outside test data: "' + testData + '" === "' + outsideTestData + '" => ' + (testData === outsideTestData) );
            }); // jQuery()

        </script>
    </head>
    <body style="background-color: silver">

        <div id="div1" class="div1" >
            <div id="div2" class="div2" >
            </div>
        </div>

    </body>
</html>
2

There are 2 answers

0
oryol On BEST ANSWER

jQuery object itself is created inside anonymous function and it uses closure for accessing global (global for other jQuery functions) array inside this functions. So, as result: jQuery in iframe and jQuery in the top window have different data array. If you need top level data, use window.top.jQuery('#div1').data('test1') (please note that default context for jQuery is document, where it was initially created, so using "top level jQuery" we don't need to specify top level document.

0
Gideon On

Have a look at Ben Alman's jQuery postMessage plugin