Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access jQuery data from iframe element

Tags:

jquery

iframe

Lets say I have a page on the same domain that I put inside an iframe. In the iframe, I have added data to an element, something like this:

HTML

<div id="data"></div>

Script

$('#data')
    .data('test1', 'this is test data 1')
    .data('test2', ['John', 'Smith'])
    .data('test3', {
        alert1: function() {
            $('#data').append('test3: successful<br>');
        }
    })

Now once this page is in an iframe, I know I can access the element as follows:

$('#frame').contents().find('#data');

But when I try to get the data from that element, it's always undefined.

$('#frame').contents().find('#data').data('test1'); // shows up as undefined

I know jQuery stores data() internally in a cache object, but I don't know how to access it from outside that document. I set up this demo to display my problem. Click the "Get Frame Data" button to see the results.

I would appreciate any input :)

like image 549
Mottie Avatar asked Nov 04 '10 21:11

Mottie


2 Answers

You need to get the cache element from that window's jQuery object, like this:

var windowjQuery = $('#frame')[0].contentWindow.$;
var f = $('#frame').contents().find('#data');

Then to get data, use $.data(), like this:

windowjQuery.data(f[0], 'test1')

You can test out your updated/working demo here.


What this is really accessing is:

var key = f[0][frame.contentWindow.$.expando];
var dataItem = frame.contentWindow.$.cache[key]["dataKey"];
like image 140
Nick Craver Avatar answered Oct 20 '22 08:10

Nick Craver


I have never tried this, but I'm pretty certain you need to talk to the iframe's $ object instead of your document's one to access that object's internal data storage. Not 100% sure how to do that - maybe something like

$('#frame').contents().jQuery.find("#data").data("test")

(wild guess)

What would work for sure is a function inside the iframe document that fetches the data, and returns it to you. But that's much less elegant than fetching it directly, of course.

like image 28
Pekka Avatar answered Oct 20 '22 08:10

Pekka