Getting the html content of an iframe using jQuery

2019-01-16 12:42发布

问题:

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.

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');

回答1:

.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.



回答2:

you can get the content as

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

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



回答3:

I suggest replacing the first line with:

  var editFrame = $('#ta_OpenCmsHtml.LargeNews_1_.Teaser_1_.0___Frame');

...and the 2nd alert expression with:

  editFrame.html()

If, on the other hand, you prefer to accomplish the same w/o jquery (much cooler, IMHO) could use only JavaScript:

  var editFrame = document.getElementById('ta_OpenCmsHtml.LargeNews_1_.Teaser_1_.0___Frame');
  alert(editFrame.innerHTML);


回答4:

I think the FCKEditor has its own API see http://cksource.com/forums/viewtopic.php?f=6&t=8368



回答5:

Your iframe:

<iframe style="width: 100%; height: 100%;" frameborder="0" aria-describedby="cke_88" title="Rich text editor, content" src="" tabindex="-1" allowtransparency="true"/>

We can get the data from this iframe as:

var content=$("iframe").contents().find('body').html();
alert(content);