Getting Contents of Iframe with Pure JavaScript

65,814

If it is on the same domain, try this. It won't let you access iframe contents if the iframe is of a different origin than the window that you are viewing.

var iframe = document.getElementById("awc_frame");
var iframe_contents = iframe.contentDocument.body.innerHTML;

Working example with jsfiddle iframe viewing a page on the same domain:

http://jsfiddle.net/tqAL3/1/

Share:
65,814

Related videos on Youtube

EasyBB
Author by

EasyBB

I am a self learning developer/designer. I've been writing HTML since 2000 and still up to with the specifics of HTML5! CSS is another great coding language of mine, loving the CSS3 3D transforms and everything about it! I first started learning jQuery in 2012 and well that was a big mistake, so now I write everything in Vanilla JavaScript, it renders quicker and is a lot faster than going through a library.

Updated on July 09, 2022

Comments

  • EasyBB
    EasyBB almost 2 years

    I already can get the content of an Iframe with jQuery, though I would like to learn how to get it with pure JavaScript.

    This is what I have so far.

     var frame = document.getElementById('awc_frame');
     var easyBB = frame.contentWindow.document.body.innerHTML;
     easyBB.getElementById('chatbox-title').innerText="Chatbox";
    

    What am I doing wrong, please help. Also originally the frame does not have an ID, and I already tried this

    var frame = document.frames['awc_frame'];
    

    Is that cross browser efficient? And then how do I get the contentWindow? Just some explanation so I can do this with JavaScript and not jQuery. jQuery version is this

    var frame = $('#avacweb_chat iframe');
    var easyBB = $('#chatbox-title',frame.contents()).text('Chatbox');
    
    • Ciro Santilli OurBigBook.com
      Ciro Santilli OurBigBook.com about 10 years
    • Ciro Santilli OurBigBook.com
      Ciro Santilli OurBigBook.com about 10 years
      sorry, no offense intended. Is there a community consensus (e.g. Meta question) that says that it is not good to mark as duplicates of old questions? Do you agree that they are the same question? If not, can you explain why? I may have misjuged.
    • EasyBB
      EasyBB about 10 years
      Well yes different. Sorry for my rudeness just was irritated. Different as I show my code, both jquery and vanilla and that question shows no code from the OP
  • Ciro Santilli OurBigBook.com
    Ciro Santilli OurBigBook.com over 9 years
    Specified at: w3.org/TR/html5/…
  • Rayjax
    Rayjax over 8 years
    what if I want the HEAD with it ? Do I have to do contentDocument.head.innerHTML and concatenate to the body or is there a faster way
  • Rayjax
    Rayjax over 8 years
    nevermind -> iframe.document.getElementsByTagName('html')[0].innerHTML