2014-05-19 124 views
1

我目前通過XHR接收網頁的某些部分,然後使用DOMParser解析它們。在此之後,我更改了一些元素,但我無法將文檔附加到iFrame。將文檔附加到iFrame

被解析的文檔是好的,但是當通過調用iFrame.contentDocument = parsedDocument將添加到iFrame中時,它保持爲空(實際上有html,head和body標籤,但它們的內容是空的)。

我解析接收到的數據,像這樣:

var parser = new DOMParser(); 
var parsedDocument= parser.parseFromString(xhr.response, 'text/html'); 

而且我的期望是做這樣的事情:

iFrame.contentDocument = parsedDocument; 
+0

如果你寫信給它? 'var doc = document.getElementById('iframeId')。contentWindow.document; doc.open(); doc.write(parsedDocument); doc.close();' – epascarello

+0

@epascarello它現在在iFrame中顯示'[object HTMLDocument]'。 – MarijnS95

+0

@ MarijnS95然後你應該嘗試'xhr.response'而不是'parsedDocument'。 'parsedDocument'是一個'HTMLDocument'對象,而您想要寫實際的字符串,否則它會嘗試寫'HTMLDocument.toString()',它將返回'[object HTMLDocument]'。 – Joeytje50

回答

1

像epascarello在評論中說,下面的工作:

var doc = document.getElementById('iframeId').contentWindow.document; 
doc.open(); 
doc.write(xhr.response); 
doc.close(); 

但是,由於您需要在將文檔放入ifra之前修改文檔我,你首先需要做的是:

//your code 
var parser = new DOMParser(); 
var parsedDocument = parser.parseFromString(xhr.response, 'text/html'); 
//put your required edits here 
parsedDocument.getElementById('foo').style.color = 'red'; //example 
//now to get back the edited HTML code as a string 
var newHTML = parsedDocument.documentElement.outerHTML; 
//and now for the code epascarello mostly wrote 
var doc = document.getElementById('iframeId').contentWindow.document; 
doc.open(); 
doc.write(newHTML); 
doc.close(); 

您可能還需要有指定的doctype,用替換的doc.write(newHTML);行:

doc.write('<!DOCTYPE html>'+ newHTML); 

因爲document.documentElement.outerHTML將不包含與它的文檔類型。