将文档附加到iFrame

时间:2014-05-19 19:16:34

标签: javascript html iframe xmlhttprequest

我目前正在通过XHR接收部分网页,然后使用DOMParser对其进行解析。在此之后我更改了一些元素,但是我没有将文档附加到iFrame。

解析的文档没问题,但是当通过调用iFrame.contentDocument = parsedDocument将此文档附加到iFrame时,iFrame.contentDocument保持为空(实际上有html,head和body标签,但其内容为空)。

我正在解析收到的数据,如下所示:

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

我的期望是做这样的事情:

iFrame.contentDocument = parsedDocument;

1 个答案:

答案 0 :(得分:1)

就像epascarello在评论中所说,以下内容将起作用:

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

但是,由于您需要在将文档放入iframe之前修改文档,因此您首先需要执行此操作:

//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不会包含带有它的doctype。

相关问题