Kurkula
Kurkula

Reputation: 6762

Jquery read parent value from iframe

I am trying to read a username which is out side iframe. How can I get the parent value out side iframe on clicking button inside iframe?

Here is my fiddle

<span id="user">
My Name
</span>

<iframe id="my-iframe" height=200 width=300>
<input type="button" id="myButton" value="click">
</iframe>

$('#myButton').click(function(){
var userName = $('#user').text();
alert(userName);
});

Upvotes: 0

Views: 116

Answers (1)

Andrew Tevington
Andrew Tevington

Reputation: 193

I wasn't aware that you could have an iFrame without a source, but apparently you can. I'm not sure why you're doing this, but it appears that you must write to the iFrame itself instead of nesting the elements inside. For example:

var iframe = $("#my-iframe")[0].contentWindow.document;

$("body", iframe).html("<input type=\"button\" id=\"myButton\" value=\"click\">");

Note that you can only access the contents of an iFrame if the parent and child are on the same domain and protocol. I guess an iFrame "literal" as in your case is counted as the same origin.

Also, since your click binding is run in the parent window, it's only searching for elements in the parent document. You must tweak your selector so that it searches the iframe document instead:

var iframe = $("#my-iframe")[0].contentWindow.document;

$("#myButton", iframe).click(function(){
    var userName = $("#user").text();
    alert(userName);
});

The same origin policy applies to the above as well.

Full fiddle here.

Upvotes: 1

Related Questions