2012-01-11 112 views
19

我目前正試圖自定義OpenCms(基於Java的開源CMS),它使用嵌入的FCKEditor,這是我試圖使用js/jQuery訪問。使用jQuery獲取iframe的html內容

我嘗試獲取iframe的html內容,但是總是得到null作爲返回。 這是我嘗試獲取來自iframe的HTML內容:

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 (!!) 

望着截圖中,我要訪問的是「LargeNews1 /傳情」 HTML部分,其目前持有的價值觀「時事開講恩...「。 下面你還可以看到Firebug中的html結構。

但是,$(editFrame).contents().html()返回null,我不知道爲什麼,而$(editFrame).attr('id')返回正確的ID。

iframe內容/ FCKEditor位於同一站點/域,不存在跨站點問題。

enter image description here

iframe的

HTML代碼爲http://pastebin.com/hPuM7VUz

更新時間:

這裏是一個可行的解決方案:

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

回答

46

.contents()HTML()不工作得到一個iframe的HTML代碼。你可以做到以下幾點:

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

這應該返回iframe中的所有html給你。或者,您可以使用「body」或「head」而不是「html」來獲取這些部分。

+0

謝謝,許多有用的答覆完全;我編輯了我的問題,並在底部添加了最終解決方案。 – 2012-01-11 09:36:16

+2

這適用於Firefox,但不適用於Chrome。我剛剛得到。 – user3411192 2016-09-07 21:02:40

2

我建議用替換第一行:

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

...和第二警報表達:

editFrame.html() 

如果,另一方面,你願意來完成相同的W/ØjQuery的(冷得多,恕我直言)可以使用只有JavaScript:

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

jQuery對於有點的DIV不能很好地播放。在id中,我不能很容易地更改FCKEditor組件的id(很容易)。我將對以上測試提出建議,並將在稍後發佈解決方案,我終於使用了該解決方案。謝謝大家。 – 2012-01-11 08:38:24

0

你的iframe:

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

我們可以從這個iframe中獲取數據 as:

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