Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the HTML content of an iframe using jQuery

I'm currently trying to customize OpenCms (java-based open source CMS) a bit, which is using the FCKEditor embedded, which is what I'm trying access using js / jQuery.

I try to fetch the html content of the iframe, however, always getting null as a return. This is how I try to fetch the html content from the iframe:

var editFrame = document.getElementById('ta_OpenCmsHtml.LargeNews_1_.Teaser_1_.0___Frame'); alert( $(editFrame).attr('id') );         // returns the correct id alert( $(editFrame).contents().html() );  // returns null (!!) 

Looking at the screenshot, the what I want to access is the 'LargeNews1/Teaser' html section, which currently holds the values "Newsline en...". Below you can also see the html structure in Firebug.

However, $(editFrame).contents().html() returns null and I can't figure out why, whereas $(editFrame).attr('id') returns the correct id.

The iframe content / FCKEditor is on the same site/domain, no cross-site issues.

enter image description here

HTML code of iframe is at http://pastebin.com/hPuM7VUz

Updated:

Here's a solution that works:

var editArea = document.getElementById('ta_OpenCmsHtml.LargeNews_1_.Teaser_1_.0___Frame').contentWindow.document.getElementById('xEditingArea');                         $(editArea).find('iframe:first').contents().find('html:first').find('body:first').html('some <b>new</b><br/> value'); 
like image 271
Mathias Conradt Avatar asked Jan 11 '12 05:01

Mathias Conradt


People also ask

How can I get iframe HTML code using jQuery?

# jQuery Code to Get HTML Content of IFrame$("#myButton"). on('click', function() { alert($("#myIframe"). contents(). find("html").

Can you access the content of an iframe?

The . contents() method can also be used to get the content document of an iframe, if the iframe is on the same domain as the main page.

How do I access iframe elements?

Getting the element in Iframeconst iframe = document. getElementById("myIframe"); Now, it has and contentWindow property which returns the document object by using that we can access the elements from an Iframe. const iWindow = iframe.


1 Answers

.contents().html() doesn't work to get the HTML code of an IFRAME. You can do the following to get it:

$(editFrame).contents().find("html").html(); 

That should return all the HTML in the IFRAME for you. Or you can use "body" or "head" instead of "html" to get those sections too.

like image 145
Tim Avatar answered Sep 22 '22 11:09

Tim