Get the content of an Iframe in Javascript – crossbrowser solution for both IE and Firefox

Ok, let’s imagine the use case: I have an iframe somewhere on my page, and when I click a link or a button I need to get the content of it (could be a textarea e.g.), and then do some stuff with it.

It was easy to do this in IE, but for Firefox I struggled more, as I kept getting the “frame has no properties” error message in the console. And when I solved this I couldn’t get to the content.

There is a lot of references out there claiming that you could use document.frames[‘nameOfMyIframe’] or window.frames[‘nameOfMyIframe’] to get the frame, and then use the .innerHTML to get the content, but both are wrong.

I came up with the following function that seems to do the job in both Firefox (tested on version and 3.03 ) and in IE (6 and 7):

function getContentFromIframe(iFrameName)

    var myIFrame = document.getElementById(iFrameName);
    var content = myIFrame.contentWindow.document.body.innerHTML;

    //Do whatever you need with the content    


This wasn’t my biggest contribution, but I spent some time trying to find this solution, and for some of you it might be helpful saving you frome some heavy googling.

Because of some postings about people struggling to get this to work, I now include an example using this script. The example consist of two files, main.html and frame.html. If you want to try it locally, put both of them in the same folder and open main.html.



<script type="text/javascript">
function getContentFromIframe(iFrameName)

    var myIFrame = document.getElementById(iFrameName);
    var content = myIFrame.contentWindow.document.body.innerHTML;

    alert('content: ' + content);    

    content = 'The inside of my frame has now changed';
    myIFrame.contentWindow.document.body.innerHTML = content;




<a href="#" onclick="getContentFromIframe('myIframe')">Get the content</a>






This is inside my frame


103 Responses to “Get the content of an Iframe in Javascript – crossbrowser solution for both IE and Firefox”

  1. Handyguy Says:

    Hey – I think this is getting close to what I’m looking for. I will try and be clear, maybe you could expand on this a bit.

    In WordPress I have two static pages, for sake of discussion lets call them A and B.

    Page B contains an IFRAME URL to another site.

    Page A is my main page that shows my WP posts.
    In my posts I want to provide a link to page B AND set what URL is shown in my IFRAME.

    I have played around with some JS but haven’t gotten too far. I am not really an expert in JS or PHP but I’m willing to do it were ever.

    Actually it will eventually go into PHP I think because I will be generating the link with another WP plugin. I just want to be able to figure out the URL I will need really.


  2. roneiv Says:


    And thank you for having interest in my post. 🙂

    But when it comes to wordpress, it is my understanding that they don’t allow for javascript:

    And I must admit my knowoedge of php is very limited, so I don’t know if I can help you that much. But instead of doing this with javascript, is there a way (through php) that you can have you IFRAME in page B display a url that is held by some property? The src attribute in IFRAME points to some server-side object and property I mean.

    Let’s say you have a class in PHP named PageManager or whatever, and it has a property named URL. By default it is empty (so your IFRAME on page B would display nothing). But when you click your link in page A, you set the url into the url-property of PageManager, and when page B then refreshes it would display that content?

    Possibly (me not knowing too much of php) is it an option to pass the url you want to display in page B as a parameter on your link like this: href=””, and then retrieve it from request on page B, something like “request.getParameter(“url”);” ?? And then set this value to the src of your IFRAME.

    I’m sorry I can’t help you more on this matter 🙂

  3. Frances Berriman Says:

    Thank you! This came in use today after spending way too long wondering why document.frames didn’t work.

  4. roneiv Says:

    Hi Frances,

    Glad the post I made could help you, very often it’s the small things we spend hours and hours on. 🙂

  5. Piero Says:

    thanks for posting this examples, i have my own questions… i have a html or php main page ok…and it has a iframe on the page that load an external webpage, i am trying to get the URL of the frame, everytime it refresh, throuth PHP or Java script, if you can help me (you the one is reading this), please email me o post it here. thanks.

  6. roneiv Says:

    Piero, I’m not sure about what you’re asking 🙂

    You have an Iframe, where the src is an external webpage like And then if your Iframe refreshes (I guess you mean that if the user clicked a link and went to anoter url – e.g.), you want to know or get the “new” location of your Iframe?

    I believe this is not possible if the content is external, because you’re not allowed to access the DOM across domains. And both IE and FF will throw you “Access/Permission denied” exceptions if you try to access something like “myIFrame.contentWindow.document.location”

    Is this your question or am I wrong? 🙂

  7. Matic Says:


    I have a problem too. I have a frame that loads an external site. I do not have any access to this site, so I can’t change anything on the other side. What I need to do is, to scroll the loaded page to the right position. Is there a way to scroll the page from my website. Is there a way to tell the frame to scroll to a certain position?

    Thanks for you time…

  8. roneiv Says:

    Hi Matic,

    Sorry I haven’t replied you, I’ve been away for some days and haven’t had an internet connection. But as far as I know it is not possible to scroll the page to a specific position. This is because you’re not allowed to access the DOM of the external site.

    I guess your only chance would be if there exists predefined “Destination anchors” on that page, so that you could use them in your url, something like:



  9. matt H Says:

    Thanks for this post. I had spent nearly two days trying to resolve the issue of why document.frames[iframeName] would not work in FF! This simple solution has solved my problem. Cheers

  10. Dhanya Says:

    It was very helpful . please give him big hands .

    Thanks a lot . 2 days i spent on google. at last done .

  11. Fuki Says:

    Your solutions are simple but no one can think out! Thank you so much

  12. Kitten Says:

    how come this is not working:

    function getIFrameSource(iFrameName)
    var myIFrame = document.getElementById(iFrameName);
    var content = myIFrame.contentWindow.document.body.innerHTML;

    • tomy Says:

      LOL this is way late but I can help those poor users out there that have the same problem. You have quotation marks around “content” meaning that it will literally print “content” instead of the actual content. Remove the quotation marks (JS does not parse strings like PHP).

  13. Kitten Says:

    My error is

    Line7 this is my var myIFrame line

    Object Required

    i have an iframe and the names match but i get an error

    • Avi Says:

      var myIFrame = document.getElementById(iFrameName);
      is wrong because iFrameName is not an object. add this:
      var myIFrame = document.getElementById(‘iFrameName’);

      missing quotes

      • roneiv Says:


        No you’re wrong unfortunately. 🙂
        The iFrameName is a parameter passed through the function, hence it’s an object and should not be wrapped inside quotes.

        Your version would look for an iframe named “iFrameName”, but we want to look for the name that is passed in the function.



    • tolga Says:

      does the iFrameName var carries an iframe’s name or id?

  14. roneiv Says:

    Kitten, I do not see anything wrong immediately, but I am not used to pass the alert throug document object. Simply write alert(); Also, you should not use quotes around an object if you want to print it, just alert(content); Using single-quotes instead of double ones is also a good idea 🙂

    When it comes to the problem with the IFrame, perhaps you can use Firebug (or some broser debugger) to check the name of your iframe in the dom – cause the name you pass to your function should match this exactly.



  15. dan Says:

    I have an iframe on one site which loads simple HTML page from another site.

    I want to get that raw HTML code that is in the IFrame.

    Can I do this?


  16. roneiv Says:


    No you can not 🙂 The dom of that external source is not accessible by you 🙂

    – E –

  17. Vítor Says:

    doesn’t work on firefox

  18. Juliano Says:


    I am loading an iframe from an external URL and would like to know if the loading process has gone well. If it has not then I may load another URL and maybe process each URL from a list.

    How can I check if the iframe loading has gone well ?

    If not an iframe, what else could permit me to do that ?

    Thank you,

  19. roneiv Says:


    Can I ask which version of firefox you are using?

  20. roneiv Says:


    I’m not sure if what you’re asking is doable from the dom. For sure you cannot access the dom of your externalURL.

    I suggest you remove this responsibility from the iframe and find a way of testing the validity of your url(s) before you try to load them into your iframe.

    Goto this page and search for “Does a url exist?”

    Or java-side, use something like the org.htmlparser.Parser to go through your list of URL’s and depending on the status-code you filter them out.

    Hope this helps!

  21. Juliano Says:

    The webpage you provided is very interesting roneiv.

    If I understood what is explained on it I have to create a new ActiveXObject(“Msxml2.XMLHTTP”) in order to use the “xmlhttp” functions which will permit me to test availability of a webpage (which is exactly what I want to do).

    But will IE prompt a security warning when trying to create the ActiveX Object ?

    Moreover is that Mozilla compliant ?

    Thank you for assisting me

  22. roneiv Says:


    I guess you can use the code you find on that page (under the section “Creating the object”) to create the ActiveX-object. As you see it first tries to create the xmlhttp object with explorer, then if both of them fail it tries the mozilla way, and if this one fails as well it tries the alternative for Ice browsers.

    As far as I know there shouldn’t be a security warning in IE, and the xmlhttp is crossbrowser compliant – yes. The only different thing is the way you instanciate the object, but the code snippet I have talked about handles this for you.

    If you need some more info on AJAX it could be nice for you to check some of the tutorials like:



  23. Anish S Pillai Says:

    Dear roneiv,

    Thanks very much for ur valuable contribution.This is what i was searching for.
    once more Thanks very much.
    Please keep contributing valuable information like this.

  24. extra Says:

    I’m using firefox 3. This is my page’s code:


    function a()

    var myIFrame = document.getElementById(“frame”);

    content = “dasdf”;


    That means when press the button the text on “alphatest.html” change. But it doesn’t work. what is the prob??

  25. Shaik Amjad Says:

    Hi roneiv, it’s perfect! keep it buddy

  26. roneiv Says:


    I’m not sure if I get your problem.

    As far as I understand you have an iframe with src set to “alphatest.html”. Then, if you press change, the content of the iframe should change to ‘dasdf,’ is that it?

    In that case you just need to set the innerHtml property to the new content:

    myIFrame.contentWindow.document.body.innerHTML = content.

    Your iframe should now display dasdf instead of the page alphatest.html

    But if you thought that this operation would physically do a write to the file alphatest.html and modify it, I’m sorry to say that it wouldn’t work – it is not possible.



  27. Steven Says:

    Don’t work fr me in FF3…

  28. roneiv Says:


    That’s strange, cause I recently tested it in my FF3 and it worked well.. ??

    But I use the 3.0.1 version of firefox then, still I don’t think this should matter. (Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv: Gecko/2008070208 Firefox/3.0.1)

    What problems do you get?



  29. D Mux Says:

    FireFox 3 has high security when it comes to cross site scripting. It does not allow code to access sources from other domains on the same page. For that you have to either use signed javascript or override the FF3 security by using“UniversalBrowserRead”);

    Browsers older than FF3 don’t enforce this kind of rules for XSS.

  30. Rochak Chauhan Says:

    I tried the above code in Firefox 2


    it said:

    uncaught exception: Permission denied to get property HTMLDocument.body

    Any idea how to overcome this ?

  31. roneiv Says:


    If the content of your iframe is from another external site you are not allowed to access the body of that document. Hence the permission denied exception.

    But if it is displaying a local resource then I don’t really understand what’s going on??



  32. Stu Says:


    An issue I have that I cannot quite overcome and unfortunately I’m new to javascript but versed in programming in general. It is similar to what you have here but it is in the other direction-
    My parent window opens the iframe document inside the page. Inside the iframe document I will have thumbnails for my photos but I want them to be opened on the parent window using slimbox (similar to lightbox)

    If I simply click on the thumnail as is inside the iframe, slimbox opens up inside the iframe, not full screen. This did not surprise me but I don’t know how to pass that information to the parent page.

    Thank you in advance!

  33. roneiv Says:


    I’m not familiar with slimbox but I had a quick look and I saw that it was possible to open the image the following way:“images/image-1.jpg”, “Spheres in construction”);

    So if you inside the parent window declare a javascript function (inside body tags) like this:
    function openBySlimbox(imagepath, imagetitle)

    This function will pass the parameters to the function.

    From your iframe you call the parent javascript function like this:


    Do you think this would help?



  34. Graham Says:

    Kudos, exactly what I needed after some moderate googling! ; )

  35. Sean Says:

    Doesn’t work in IE 7 guys 😦

  36. roneiv Says:


    I don’t know why you don’t get it to work, but it works for me in IE7?? Do you get any error messages?

    Try to use the example I’ve provided now and see if it works then?



  37. Amir Hussein Latifi Says:

    Great trick and nice format!

  38. didin Says:

    thanks bro.. nice blog….

  39. orlandooo Says:

    Hi, Is there a workaround to get the new location of the iframe, when it points to an external website and they navigate inside that website through the iframe? I’ve spent a lot of time searching a solution but the access denied problem remains…help!!

  40. roneiv Says:


    Sorry – but I don’t think you will be able to find a solution to your “problem”. The dom of that external website is not accessible to you, so you can’t get the new location of the iframe because of permission problems.



  41. Az Says:

    “myIFrame.contentWindow” work only in IE
    using “myIFrame.contentDocument” for FF

    Here is my modify:

    function getContentFromIframe(iFrameName)
    var myIFrame = document.getElementById(iFrameName);
    var content = navigator.userAgent.indexOf(‘MSIE’) != -1 ? myIFrame.contentWindow.document : myIFrame.contentDocument;
    return content;

  42. Magnum Says:

    Thanks for solution!

  43. polluxx42 Says:

    *Works in Firefox / Safari OS X – Firefox however will not display the contents of an iframe if the content is external (from another site).

    Kitten, you need to remove the quotation from around your variable name. Variables are accessed directly, adding quotations will alert the text string “content.”


  44. HD Says:

    It doesn’t work, because it’s not supposed to.

    • roneiv Says:

      HD, It’s not supposed to work if the iframe contains an external source, but if it holds a resource within your context root for sure it should work.

  45. Adam Says:

    Great! Awesome! Exactly what i was looking for!

    Thanks a lot!

  46. bigD Says:

    Thanks.. this saved my day…. 🙂

  47. Frank Says:

    Unfortunately this does not conform to xhtml. The iframe element should not have an “id” attribute.

    Could something like this work?


    This would allow you to insert content from another page in an iframe.

  48. Frank Says:

    IF you think about it, there is no content between the tags. This is why some people get nothing when they give the iframe an id, and try innerHTML.

    I think the proper thing would use seomthing along the lines of:

  49. sergiozambrano Says:

    I’ve been able to read the content of external websites with a modified version of a script called code viewer

    So if this can print the page code to the screen… it should be able to print it to a ‘write’ command.

    Am I right?

    function showcode($urltest) {

    $path = 'http://' . $urltest;

    // Open the file
    // If the file can't be found, print an error message
    if ($lines = @file($path)) {
    $codelist = '' . "\n";

    foreach ($lines as $line_num => $line) {
    $toggle = (($line_num % 2 == 0) ? "odd" : "even"); // set alternating class names for each line

    // If the line is blank, insert a space to prevent collapsing
    // Otherwise insert the line
    if (ltrim($line) == "") {
    $codelist .= "\t" . ' ' . "\n";
    } else {
    $numtabs = strlen($line) - strlen(ltrim($line)); // determine the number of tabs
    $line = trim($line); // trim leading/trailing whitespace

    $codelist .= "\t" . '' . htmlspecialchars($line) . '' . "\n";

    $codelist .= "";
    } else {
    $codelist = '[The requested file ' . $path . ' could not be found]';
    return $codelist;

    • sergio Says:

      Ok, this is the deal.
      I’ve managed to read and EXCTRACT content from external websites with the above php.

      The problem is… websites loaded from the server need a fake “session” (I didn’t even try it because it sounded too difficult to me) to “believe” they were loaded from the browser, otherwise the external website may detect it and deny the content. E.g. If you have to log in for that page, your cookies won’t be present on the server (where your php is executed) and you won’t see the same page you see in your browser.

      If your page loads, only the first page will be loaded from your php server. Every click after that won’t be loaded thru the php page, but from your browser, so there ends the magic.

  50. Ghostface Says:

    Just in case, somebody else is looking for it.

    Evaluating if anything has been written inside a tinyMCE textarea:

    var inymce_content=$(‘text_ifr’).contentWindow.document.getElementById(‘tinymce’).innerHTML;


    if(tinymce_content==””) { alert(‘please provide some text’) }

    Requires prototype tho.

  51. delic Says:

    Thanks! So simple so perfect :DDD
    In order to find url of the iFrame:
    var myIFrame = document.getElementById(“CONTENT”);
    var content = myIFrame.contentWindow.location;

  52. serzh Says:

    Many thanks! Perfect solution!

  53. Andy Says:

    woahhhhhhhhhh thank you very much. i have been killing myself for hours trying to figure out why i can’t access the iframe’s innerHTML!! my wife thanks you because NOW i can go to bed.

  54. Homer Automation Says:

    Is there a way to overcome the cross-site limitation – the error “Permission denied” mentioned previous?
    I need to access information available on other domain.

    • roneiv Says:


      Sorry but there’s a reason for why the permission is denied – and I don’t think there are any ways around it. Not as I know of at least.

      – E –

  55. Tiago (From Brazil) Says:

    Thank you very much!

  56. Nidheesh Says:

    How can I get the contents of an external iframe in IE

  57. Stanley Says:

    Thank´s a lot… you made my day 😉

  58. RaphaelDDL Says:

    Great post.
    Very useful. thank you very much

  59. debt term Says:

    @Rebecca, you seem to know what you are talking about. Would you mind shooting me your mail address? I would like to speak more with you.

  60. Drent Says:

    This is one big giant help. you have no idea how i struggled with crossbrowser javascript. I almost wanted to use a php file parser to parse the url for elements and tags.

  61. Shilpa Sathya Says:

    Thanks a ton!! Just what I was looking for 🙂

  62. lordadmira Says:

    Hi. I understand that there is the security issue for accessing other frames’ content. If not for this then some malicious website in one frame could steal the content in another frame which could have sensitive information in it.

    However. What I want to do is load data files from URL’s that could be on any domain that is not interpreted or rendered by the browser as with frames or scripts. There’s no cross domain limitation on loading images. So there should be some likewise way of getting arbitrary data into a variable. Thanks.

  63. Richard Bos Says:


    Your article helped me fix a problem in Dynamics CRM!

    Thanks 🙂


  64. web1 Says:

    All codes posted here not work. Cross-scripting is not permitted !

  65. Sokun Says:

    Thanks! it’s very useful 🙂

  66. René J. Pollesch Says:

    Thank you very much, you’ve saved my day 🙂

    Greetings from Stuttgart/Germany,

  67. Me Says:


  68. Arpita Says:

    Hi ,
    I am loading a PDF form in iFrame and user is required to fill this form and I need to extract the data of the form which is embedded in iframe , i donot know .. how to get the data and save it in database and retrieve and again fill the pdf, on login.

    Thanks in advance for any help in this regard.


  69. Online Says:

    Thank you for this tutorial.
    I looked for something like this with JS and i just found it here. 🙂

  70. raksh Says:

    I have prob in iframe…I create a file field inside my iframe .but from my page when I click the button the iframe click() event doesn’t work..
    here is my code..
    when I click the button in my jsp page.
    function browseDocsForAssignment(i)
    var mode = document.getElementById(“chkMode”).value;
    var divIdName = ‘atchFile’+parseInt(i);
    var iframeAsgntDoc = document.getElementById (‘iframeAsgntDoc’).contentWindow.document;

    { var file = iframeAsgntDoc.createElement(“input”);
    file.setAttribute(“type”, “file”);
    file.setAttribute(‘name’,divIdName); iframeAsgntDoc.frmAssignmentPlan.appendChild(file);

    …………………………………in My.jsp………………………….


    the .click() method does work in IE but not in Mozilla Firefox and other browser

    Thanx in advance…………………….
    please help me immediately……….

  71. rohan Says:

    Thank you very much….exactly what I was looking for…

  72. michael Says:

    nice …. but why my return was blank ?

    seems like can’t fetch iframe source..

  73. raphie Says:

    Hey roneiv… thanks a lot, this seems to fix a problem I had, I’m not in my computer now, but I will try it at soon as I’m in my house.

    I’m using Ajax to save the information of input fields into a database but the openwysiwyg that turns the textarea into a wysiwyg makes an iframe and I couldn’t be able to make it grab the content of the iframe and store it in the textarea that’s what’s dynamically the Ajax code reads.


  74. Taobao FOCUS Says:

    is there any way to disable target _blank in the iframe content??

  75. cata Says:


  76. Marius Says:

    Thanks a lot. you’ve made a great work to save time for many js begginers:)

    maybe someone knows how could i read only one DIV or something like that?

    my goal is to make js which reads only one line from content of page loaded in iframe everytime that page is refreshed.

    if someone know how to do that please let me know.
    P.S. every page loaded to iframe is from one domain but from different folders.

  77. Odin Says:

    Did you ever heard about ajax.
    Use ajax for this kind of stuf.

  78. Mark Says:

    Oh you absolute star!

    I’ve been googling this one for the last couple of days and was about to give up and turn to server-side scripting instead.

    this has saved me a loooad of hassle 🙂

  79. Adway Says:

    Dear Sir!

    Shall I request them to nominate you for Turing award next year? You have single handedly rendered a service to CS Society that could hardly be surpassed by Turing himself.

    Your solution actually works across IE, FF, Opera & Chrome.

    ext time you are in town, I’ll readily stand you a dinner.

  80. Pooja Says:

    Hi ,
    I have page where i call for another iframe. I just wanted to check if div#outer_container exists in that iframe…

    So if iframe has a content A which is in div#outer_container i wanted to set the height of iframe to 50px else i wanted to set the height to 0px ..

    I was wondering how do i check if that iframe has div tag in its body.

  81. Rizwan Says:

    I want to read the message body of hotmail message.
    But the problem, i just cant figure out how to read the body html through javascript.

    It had multiple iframe, when read almost all return null except one for which i get a security error saying not allowed.

    I want to use this idea to change the hot mail message text on the fly use Grease Monkey extension to show fake message to my friends. But i just can’t figure out how to do that.

    It is working fine on gmail and yahoo and i can change the content of any email with whatever i want. But why not for hotmail, please help.

  82. filmovi sa prevodom Says:

    Is it possible to read content of iframe if iframe is from another site?

  83. Hakan Says:

    If you want the full content of an iframe you can use:

    var content = myIFrame.contentWindow.document.documentElement.innerHTML;


  84. manisha Says:

    Is it possible to print embedded PDF in iFrame using Javascript in Firefox 4.x and more…


  85. Tomo Says:

    Your Main.html – Frame.html is not working. I need that code, can you please correct it? Thank you.

  86. Vlad Mocanu Says:

    Thank you very much ! It works great ! I’m using this trick to figure out when a file was uploaded. I targeted the upload form towards a hidden iframe and after I start uploading the file, I’m checking the contents of the iframe.

    I tried with $(“#myIFrame”).html() but it didn’t work. I kept getting the initial iframe html.

    Thank you very much !

  87. sriram Says:

    oesnot work for accessing the iframe content referrring to external web site

  88. Andras Says:

    I does not seem to work if you load up the contents of the iframe with ajax after the DOM tree was initialy build.

  89. Daniel A. Says:

    to make it work you have to add the following code to main.html

    line 22:
    line 23: Your browser does not support iframes.

    This is of course on your local machine, that is why it will work.

  90. Daniel A. Says:

    line 22: \

  91. Steve Says:

    I have created a simple auto scrolling iframe that contains the “guestbook” entries. I have been manually adjusting the “end of the page” for it to scroll to the bottom and then delay and restart from the top again. I have been looking for days for a way to get the iframe’s document height in
    the parent which contains the iframe declaration and the guestbook entries. I saw a lot of resizing the iframe/div to fit its contents. (which I do not want to do, I just wanted the $(document).height() of the guestbook entries. My solution was to define a variable in the parent and to set the value in the content of the iframe (child). Parent: var guestheight = 100; Child parent.guestheight = $(document).height();. I am not waiting for any document ready, since the iframe’s scrollHeight > 100 and once it is loaded, the parent’s guestheight variable is set to the scrollHieght of the contents of the iframe within the parent. Now I can use that to reset the scrollTo back to the top when the current scroll Y variable is greater than the guestheight. Works like a charm.

Leave a Reply to Richard Bos Cancel reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: