How to access iframe in jQuery

Assuming you have

1
  <iframe id="iframeID" ...></iframe>

Iframe contains div with id=”someID”:

1
  <div id="someID">Hello world!</div>

Need get div’s text?

1
  $('#iframeID').contents().find('#someID').html();

This entry was posted on Friday, March 21st, 2008 at 21:45 and is filed under jQuery. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.





118 Responses to “How to access iframe in jQuery”

Thanks, this was a big help. Works for me!

You’re welcome, jGeek! :)

… with this kind of thing, is’nt it possible to steal other peoples email, etc … (?)

Rog, what you mean?

i must be wrong somehow … but, this is what I thought when i read your tip :: i deliver a web page, with an iframe in it with src of mail.google.com. i hide the iframe somewhere/how, and using the jquery code, read the content and post the interesting stuff back to my original server … (?)

This didn’t work for me. One thing you must keep in mind is that just because the parent page is loaded or ready, doesn’t mean the frame is done. Here’s what i got to work:


[code]

jQuery and Frames

jQuery( function() {
$('#frame1').load( function(){
$(this.contentDocument).find('body').html('This frame was modified with jQuery! Yay!!!')
});
$('#frame2').load( function(){
$(this.contentDocument).find('body').html('This frame was modified with jQuery! Yay!!!')
});
});

jQuery and Frames

Frame from the same domain as parent.

Frame from a different domain as parent.

[code]

rog, good thinking... but browsers follow similar rules with iframes as they do with xml_http_requests: that is, it blocks cross-domain access.

For example, if I am running the above script from the page: http://www.liveintensely.com/parent.html, I can read and write to the frame which' source is http://www.liveintensely.com/frame1.html. HOWEVER, if the frame's source is on a different domain, like http://www.google.com, javascript is denied both read and write access to the frame.

Wow… didn’t know html came through when posting. Please excuse the double post.

This didn’t work for me. One thing you must keep in mind is that just because the parent page is loaded or ready, doesn’t mean the frame is done. Here’s what i got to work (the first example):


<html>
    <head>
        <title>jQuery and Frames</title>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            jQuery( function() {
                $('#frame1').load( function(){
                    $(this.contentDocument).find('body').html('This frame was modified with jQuery! Yay!!!')
                });
                $('#frame2').load( function(){
                    $(this.contentDocument).find('body').html('This frame was modified with jQuery! Yay!!!')
                });
            });
        </script>
    </head>
    <body>
        <h2>jQuery and Frames</h2>
       
        <h4>Frame from the <i>same</i> domain as parent.</h4>
        <iframe id="frame1" src="iframe.html"></iframe>
       
        <h4>Frame from a <i>different</i> domain as parent.</h4>
        <iframe id="frame2" src="http://google.com"></iframe&gt;
    </body>
</html>

rog, good thinking… but browsers follow similar rules with iframes as they do with xml_http_requests: that is, it blocks cross-domain access.

For example, if I am running the above script from the page: http://www.liveintensely.com/parent.html, I can read and write to the frame which’ source is http://www.liveintensely.com/iframe.html. HOWEVER, if the frame’s source is on a different domain, like http://www.google.com, javascript is denied both read and write access to the frame.

thanks for your reply. i couldn’t imagine that this would be possible – but it’s good to know exactly the mechanics of how it works … thanks.

Good work, very thanks.

Нема за що ))

Mike, I’m quite a jQuery noob, but:

* shouldn’t it be $(‘#frame1′).ready() instead of $(‘#frame1′).load() ? “load” doesn’t seem to trigger anything (but no errors either).

* doesn’t $(this.contentDocument) refer to the current document instead of the iframes?

you have no idea how invaluable this tidbit of knowledge has been for me

A reverse Proxy should be the right thing for your Problem. @rog

Renatogarou

Hello !
Can I use this method for acess the content of Tinymce ? How ?

Sorry my English .

Renatogarou, I think you can use this with TinyMCE, but I’m not familiar with it so unable to provide more help… Probably you can find information you’re looking for in TinyMCE API documentation.

Hi fellas.
How can I pass param(s) to load handler?

thanks a lot. it works

_ts_,
what you mean?

roberto,
you’re welcome :)

2 Taras
Thank you. I’ve already found the solution for my question.

But I’ve another one.

if iFrame has some function named as “someFunction” and how can I call this function from parent window?

Thank you!

sure… just:
[code]
frameId.someFunction(params);
[/code]

(assuming )
at least that works in firefox 3.0.10…

cheers, matt

Hi, I’ve looked at the code suggested by Taras and Mike; thanks guys. But I found that neither of them work very well. Jquery converts HTML objects into object objects, which restricts the abilities of manipulating iframes. I found that a better approach to address an iframe is using the best of both worlds:

var iframeRef = document.getElementById(‘iframeID’);
$(iframeRef).find(‘html’).html(‘your content here’);

Taras hey! Thank you very much!!
this tiny bit of information saved me hours of working. ^^

2 Nate:
I think, for jQuery way we can get

var iframeRef = document.getElementById(’iframeID’);

by simple:

var iframeRef = $(‘#iframeID’);

Thankyou so much, How about iframe 2 level deep (get value from iframe inside iframe).

Best regards,

hi
I’m trying to add script tag to the Head of the Iframe but it doesn’t work

can you help me with that, this is my code

$(iframe).contents().find(‘head’).html(”
+ ”);

the css file included correctly but the script tag no
any help

Thanks a ton for posting this. I didn’t read the comments but I’m sure somewhere up there, someone is trying to prove that they’re smarter than you…just the nature of being a web developer I suppose. Just know that I’m sure this little piece of code probably saved someone their job at some point…me, just saved me from losing another day of work trying to figure this out, lol.

if in reverst,

how can i out the value from the abc.com into “list”

thanks,

if in reverst,
div id=list /div

iframe src=abc.com

how can i output the value from the abc.com into “list”

thanks,

Thanks !

Good stuff here. My question is how can a script embedded in the document within the iframe close the entire jquery dialog which was called from the parent?

I have done so much in Jquery and have learned most tricks of the trade but this is probably the best thing I have ever come across. I am so excited about the endless posibilitys that this will bring. Thanks sooooooooo much for sharing!

Thaks! thats help me and work for me.

This is not working for me. Please help me for this. I am posting the jquery code here

the id of iframe is #depGridFrame

$(‘#depGridFrame’).ready(function()
{
alert($(this).contents().find(‘#updtGrid’).tagName);
});

i am calling it from document.ready function of parent document.

These iframes are getting on my nerves. I can’t get it right …

If anyone is still having trouble with selecting iframe contents w/jQuery I’ve verified this as working (keep in mind the iframe must be in the same domain as the accessing page, as mentioned above):

var myFrame = $(‘#myFrameId’);
myFrame.load(function() { // wait for iframe to load
myFrame.contents().find(‘#myElementInFrame’).html(‘hello world!’);
});

This was a very big help.
i spent hours trying to maniuplate the iframe.
thanks a lot

@Taras, @cbsides Thank you very much got it working

Karl Stanton

I found this very helpful, thank you!!

thanx a lot bro, i found this ..

hello all
what to do if the domain is different ?

i want a jquery which will hide some of the div from the the website in the iframe from the different domain.

This work for me.
$(‘#iframe-name’).contents().find(‘#frame-do-you-want-get’)

Example:
$(‘#TB_iframeContent’).contents().find(‘#wrapper’).css(‘display’,'block’);

Thanks bro.

This is all fine, but what happens if you want to get content that is sitting between two comment tags?

Example:

I follow all of you not works!

How can I do?
Can anyone help me please?

TigerLily

Thanks for posting this. It was of great help to me.

not working in external sever.

None of these examples worked for me:

$(’#iframe_name’).contents().find(’#id_within_iframe’).whatever();

var iframe_ref = $(’#iframe_id’);

$( iframe_ref ).find(‘#id_within_iframe’).whatever();

However, this did work perfectly:

var iframe_ref = document.getElementById(’#iframe_name’);

$(’#id_within_frame, frames[ iframe_ref ].document).whatever();

No solution yet?

Target Div

How do you target a DIV ID inside of the frame?

Not working:
$(“Lorem Ipsum”).insertBefore(‘#myFrame.ContentArea’);

I want to add the to a div with an ID=”ContentArea” that is inside the iFrame.

steven smith

Hi

is possible to use this for Warning Navigator when user leave this site…using beforeunload method

i have test it on without iframe… it’s fine working but when it come to iframe

it wont working with warning navigator.. cos this warning site was in iframe.. so possilbe can use this code as for warning Navigator in iframe for main site

cos i was told it’s impossible do it on this

Nyuszika7H

@Target Div:
‘Lorem Ipsum’ isn’t a valid jQuery selector.

Method 1:
$(‘#myFrame > #ContentArea’).before(‘Lorem Ipsum’);

Method 2:
$(‘Lorem Ipsum’).insertBefore(‘#myFrame > #ContentArea’);

This may also work:
$(document.createTextNode(‘Lorem Ipsum’)).insertBefore(‘#myFrame > #ContentArea’);

Nyuszika7H

Method 2, use SPAN tags around Lorem Ipsum. The site stripped them out.

Nyuszika7H

Update: $(‘#myFrame #ContentArea’)

There should be a SPACE, not a >. Sorry, my mistake.

much simpler, to target your div just do:
$(“div”,$(“iframe”).contents());

Then something like this in you case: $(“#ContentArea”,$(“#myFrame”).contents()).append(“Appended stuff”);

Targer Div

Thanks Xample. That did the trick! It works!

Nyuszika7H, I could not get your methods to work. Thanks for your help.

IE issues

This is awesome, but it only works in FF and Chrome. IE ignores all elements passed.

IE issues - another user

I’m using IE as well and the only way I could get it to work was using something similar to c.cobb’s method.

This is what I’m doing:

var frameDocument = $(‘#frameId’)[0].contentWindow.document;
$(‘#divId’,frameDocument).text();

I want to access a value of hidden variable defined in Iframe in my parent page. Please help..

$(‘#iframeID’).contents().find(‘#hidden_field_id’).val();

nulled scripts…

[...]simple » Blog Archive » How to access iframe in jQuery[...]…

come on someone give with exmple pages it is getting to complicated

i want to auto click a link in an iframe

Thanks man this really save me a lot of time!

Muchas gracias.. justo lo que buscaba

[...] 2008 at 21:45 and is filed under jQuery. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own [...]

thanks that did the trick for me! had trouble with many other examples but yours did it.

cheers

Filipo Grand

Hi thank you, It works!

Hello there I am so glad I found your webpage, I really found you by error, while I was
looking on Digg for something else, Anyhow I am
here now and would just like to say thanks for
a marvelous post and a all round interesting blog (I also love the theme/design), I don’t have time to read it all at the moment but I have bookmarked it and also added in your RSS feeds, so when I have time I will be back to read much more, Please do keep up the awesome job.

I have read so many articles regarding the blogger lovers but this piece of writing is in
fact a nice article, keep it up.

Please help me, its urgent. I am working on a website in which i need get content from iframe. code is here.

<script src="http://code.jquery.com/jquery-lates…

var myFrame = $(‘#frameDemo’);

myFrame.load(function()
{
var myjQueryObject = $(‘#frameDemo’).contents().find(‘#newid’…
alert(myjQueryObject[0].innerHTML);
});

Hi just wanted to give you a brief heads up and let you know a few of the images aren’t loading correctly. I’m not sure why but I think its
a linking issue. I’ve tried it in two different browsers and both show the same outcome.

hello there and thank you for your information – I have certainly picked
up anything new from right here. I did however expertise several technical points using this site, since I experienced to reload the site lots of times previous

to I could get it to load correctly. I had been wondering if your
hosting is OK? Not that

I’m complaining, but slow loading instances times will sometimes affect your

placement in google and can damage your high quality score if advertising and

marketing with Adwords. Well I am adding this RSS to my e-mail and could look out for

much more of your respective exciting content. Ensure that you update

this again soon..

Simply wish to say your article is as astounding. The clarity for your submit is simply nice and i could assume you are knowledgeable on this subject. Fine along with your permission allow me to grasp your feed to stay up to date with approaching post. Thank you 1,000,000 and please carry on the rewarding work.

[...] have seen several questions like this and they suggest the [...]

Heya! I know this is somewhat off-topic however I needed to ask.
Does building a well-established blog like yours take a lot
of work? I’m completely new to blogging but I do write in my journal every day. I’d like
to start a blog so I can share my personal experience and feelings online.
Please let me know if you have any suggestions or tips for brand
new aspiring blog owners. Thankyou!

simple…

UK Satellite TV Costa Blanca. British TV In Spain. Sky TV in Spain. Satellite TV in Spain. British TV Costa Blanca Spain. UK TV in Spain. UK British English Satellite TV in Spain Sky TV Freesat TV BBC TV ITV Route 4 5 and also Digital Terrestrial (TDT …

I really Believe blog post, “simple

I’m extremely impressed with your writing abilities and also with the layout to your weblog. Is that this a paid subject matter or did you customize it yourself? Anyway keep up the excellent quality writing, it’s uncommon to see a great weblog like this
one these days..

Some lenders also perform their business online, saving you the hassle of queuing for hours.
It does hold some accountability to the customers and then any good
responsible online payday advance lender will deny applications according to
their inability to meet qualification standards.

Hi, Neat post. There is a problem along with your web site in
web explorer, would check this… IE nonetheless is the market chief and
a huge section of other folks will leave out your magnificent
writing due to this problem.

Thank you for the auspicious writeup. It in truth was once a entertainment account it. Glance advanced to far introduced agreeable from you! However, how can we keep in touch?

I’ve been exploring for a little bit for any high-quality articles or weblog posts on this kind of space . Exploring in Yahoo I finally stumbled upon this web site. Studying this info So i’m glad to exhibit that I have a very just right uncanny feeling I found out exactly what I needed. I so much no doubt will make certain to do not overlook this site and give it a glance regularly.

Hey there just wanted to give you a quick heads up and let you know
a few of the images aren’t loading correctly. I’m not sure why but I think its a linking issue.
I’ve tried it in two different web browsers and both show the same results.

[...] but frame should be in the same domain refer http://simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/ [...]

My brother recommended I might like this web site. He was entirely right. This post actually made my day. You can not consider simply how a lot time I had spent for this info! Thank you!

Hi, Neat post. There is an issue with your website in internet explorer, might test this? IE still is the market chief and a huge part of other folks will pass over your magnificent writing because of this problem.

sagwltjnqmf, Propecia low fertility, jzJDqdH, [url=http://lifespeaking.com/]Rogaine vs propecia[/url], aIaLIaf, http://lifespeaking.com/ Dangers of propecia, TqEUyLU.

Its like you read my thoughts! You appear to grasp a lot about this, like you wrote the e-book in it or something. I think that you simply could do with some p.c. to drive the message house a bit, but instead of that, that is excellent blog. A great read. I will certainly be back.

gxaojtjnqmf, Dapoxetine, hRkPjjV, [url=http://www.dapoxetine123.com/]Dapoxetine sale[/url], aETPAaY, http://www.dapoxetine123.com/ To get dapoxetine, IODDfNN.

I’ve read some just right stuff here. Definitely worth bookmarking for revisiting. I surprise how much effort you place to create this kind of magnificent informative web site.

Elder Care by DELUXE GUEST HOME…

Loving facility with staff . DELUXE GUEST HOME is a awesome place for your loved one…

Howdy! This post could not be written any better! Reading through this article reminds me of my previous roommate!
He always kept preaching about this. I’ll send this article to him. Fairly certain he’s going to have a great read.
Many thanks for sharing!

Right now it sounds like WordPress is the preferred blogging platform out
there right now. (from what I’ve read) Is that what you’re using on your blog?

Heya now i’m initially in this article. I ran across this board i still find it genuinely valuable & them helped me out a great deal. I’m hoping to provide some thing yet again as well as assist others just like you assisted everyone.

Great website. A lot of helpful info here.
I’m sending it to a few buddies ans also sharing in delicious. And of course, thank you on your sweat!

What’s up every one, here every person is sharing these know-how, therefore it’s good
to read this web site, and I used to pay a visit this webpage everyday.

You could potentially certainly go to your experience within the artwork you write. This area desires more fervent freelance writers just like you whom may not be afraid to convey the way they feel. At all times follow ones coronary heart.

hey there and thank you for your info – I have definitely picked up anything
new from right here. I did however expertise some
technical issues using this website, as I experienced to reload the website many times previous
to I could get it to load correctly. I had been wondering
if your hosting is OK? Not that I’m complaining, but slow loading instances times will often affect your placement in google and can damage your quality score if advertising and marketing with Adwords. Well I’m adding this
RSS to my email and can look out for much more
of your respective interesting content. Make sure
you update this again very soon.

hi!,I like your writing so much! proportion we communicate extra about your article on AOL? I require a specialist on this area to resolve my problem. Maybe that’s you! Looking forward to see you.

I have read some just right stuff here. Certainly value bookmarking for revisiting. I surprise how much attempt you place to make the sort of fantastic informative web site.

I’m not that much of a online reader to be honеѕt but youг blogѕ
гeally nice, keeр it up! I’ll go ahead and bookmark your site to come back later. Many thanks

my website; iphone repair bangsar

Thank you for every other informative website. Where else may I get that kind of information written in such a perfect means? I’ve a challenge that I am simply now operating on, and I have been at the look out for such info.

You will be a classic superior website owner. The web site loading speed is actually awesome. It form of feels you are executing just about any one of a kind technique. Moreover, Your articles are usually must-see. you’ve done a great job with this subject matter!

Hello my friend! I want to say that this post is awesome, great written and come with almost all important infos. I would like to see more posts like this .

Too many folks have already thrown away plenty of good
money on nothing but useless salt tablets being shipped from
South America. Cucumber contains sterols which can help
to lower cholesterol and prevent carbohydrates from converting to body fat.
Many people don’t have the time to weight themselves every day, but checking the scale on a regular basis can definitely help when you’re working to lose weight and
keep it off.

Howdy! I could have sworn I’ve been to your blog before but after looking at a few of the articles I realized it’s new to me.
Nonetheless, I’m certainly happy I stumbled upon it and I’ll be bookmarking it and
checking back regularly!

There are many free online games readily available for young kids, teens, as well as grown ups.

Then came the ultra-popular Arkham games, that place
you, like never before, into Batman’s shoes as he skulks around and knocks hoodlums heads together (literaly). It is recommended that the golfers select those putters with which the golfers feel good and works well with their gaming pattern.

Recherche lié: gagner argent internet mineur

You happen to be really a very good site owner. The web page reloading rate is usually amazing. The idea sort of seems that you’ll be accomplishing any special key. On top of that, The contents will be must-see. you have completed an incredible job within this subject!

Sweet blog! I found it while searching on Yahoo News.
Do you have any tips on how to get listed in Yahoo
News? I’ve been trying for a while but I never seem to get there! Appreciate it

I think this is among the most significant info for me. And i’m satisfied studying your article. But want to commentary on some basic issues, The site style is ideal, the articles is in reality great : D. Good task, cheers

Also visit my weblog: edgy evening dress

I really like it whenever people come together and share thoughts.
Great blog, continue the good work!

I am really thankful to the owner of this site who has shared this
wonderful piece of writing at here.

As every firm is ready to give an edge over their competitors, it
is not wise to rely on ready-made or free template designs for your
website. Forum – Customers like to interact even in cyberspace.

Scripting is fine if you want to enhance the look of your website and increase its functionality,
but most of the time, it slows down the loading process especially if your visitors are using slower internet connections.

Frequently gulping down elephant-size portions of food will only make your dream of attaining
a slimmer figure only a pipe-dream. L-Tyrosine (Amino Acid) – this
is also a natural ingredient and this hormone is the one that signals the
body of being full. If you are overweight, and want to shed
weight, then read below why water can be so important for inclusion in any weight-loss program
you come up with.

Hey! This is my first visit to your blog!
We are a group of volunteers and starting a new initiative
in a community in the same niche. Your blog provided us useful information
to work on. You have done a marvellous job!

Howdy. Today using windows live messenger. Now you have an very well composed document. I am absolute to save this are available time for discover more of the very helpful facts. Just article. I am going to certainly go back.

I feel this is one of the most vital info for me. And i’m satisfied studying your article. But want to commentary on some common issues, The site taste is ideal, the articles is in point of fact excellent : D. Just right process, cheers

Leave a Reply


required


required (will not be published)