21

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');
tshepang
  • 12,111
  • 21
  • 91
  • 136
EasyBB
  • 6,176
  • 9
  • 47
  • 77
  • 1
    possible duplicate of [How to get the body's content of an iframe in Javascript?](http://stackoverflow.com/questions/926916/how-to-get-the-bodys-content-of-an-iframe-in-javascript) – Ciro Santilli OurBigBook.com Feb 16 '14 at 22:14
  • 1
    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. – Ciro Santilli OurBigBook.com Feb 17 '14 at 10:57
  • 1
    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 – EasyBB Feb 17 '14 at 13:51

2 Answers2

38

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/

Nile
  • 1,586
  • 1
  • 14
  • 25
0

The same answer as Nile but as a function more similar to the querySelector

// iframe-query-selectors.js v1
function iframeQuerySelector(iframe, selector, all){
    if( iframe && (iframe.nodeName || iframe.tagName) === 'IFRAME' && iframe.nodeType === 1){
        all = all ? 'All' : '';
        if(selector){
            return iframe.contentDocument['querySelector' + all](selector);
        };
        return iframe.contentDocument;
    };
    throw new Error('The element must be an iframe.');
};
function iframeQuerySelectorAll(iframe, selector){
    return iframeQuerySelector(iframe, selector, true);
};
Luis Lobo
  • 489
  • 4
  • 7