20

How can I work with jQuery and iframe. Get and pass var from iframe to body and from body to iframe. I have the following example. How can I click the button in iframe and make it take effect on the the body #test. How about ready var x in iframe.

<body>
var x = "whatever";
<div id"test"></div>
<iframe width="200px" height="200px" src="page.html"></iframe>
</body>

Inside page.html i have

<button>clickme</button>
<script>
var elm = $('<span>content</span>');
    elm.appendTo('#test')
</script>
amiry jd
  • 27,021
  • 30
  • 116
  • 215
Hussein
  • 42,480
  • 25
  • 113
  • 143
  • 6
    Note that most browsers will only allow manipulation of the parent document from within an iframe when both documents are from the exact same domain, as per the Same Origin Policy. – tdammers Jan 14 '11 at 08:26
  • @tdammers - Thats a good point. – LiamB Jan 14 '11 at 08:41
  • Yes. Bit me once. I had this wonderful script that would adjust the height of an iframe to its content, but it only worked on the test rig, where both pages were served from localhost :-( – tdammers Jan 14 '11 at 10:45
  • can anyone tell me that how pass value dynamically of src ? – ketan italiya Dec 17 '13 at 12:21

3 Answers3

35
$("#myid", top.document); 

or

$("#myid", parent.document.body); 

This will give you access to the container of the IFRAME

as per : http://groups.google.com/group/jquery-en/browse_thread/thread/5997ef4a60a123af

LiamB
  • 18,243
  • 19
  • 75
  • 116
  • Ive used it in the past. Can you update your question to include your new code then? – LiamB Jan 16 '11 at 12:42
  • 4
    Note, that the frames must be in the same origin for this to work. http://en.wikipedia.org/wiki/Same_origin_policy – jcoffland Jan 12 '13 at 01:11
14

From the parents perspective:

var iFrameValue = $('#iframe').get(0).contentWindow.myLocalFunction();

OR

var iFrameValue = $('#iframe').get(0).contentWindow.myLocalVariable;

From the iframe perspective

<script type="text/javascript">

var myLocalVariable = "hello";

function myLocalFunction () {
    return "hello";
}

</script>
mattdlockyer
  • 6,984
  • 4
  • 40
  • 44
sparkyspider
  • 13,195
  • 10
  • 89
  • 133
2

You can use contentWindow and contentDocument properties, if same origin poilicy is not a problem. I've setup a demo. View code for the demo and code for iframe.

Salman A
  • 262,204
  • 82
  • 430
  • 521