Javascript 将文档附加到iFrame
我目前通过XHR接收网页的一部分,然后使用。在此之后,我更改了一些元素,但是我无法将文档附加到iFrame 解析的文档没有问题,但是当通过调用Javascript 将文档附加到iFrame,javascript,html,iframe,xmlhttprequest,Javascript,Html,Iframe,Xmlhttprequest,我目前通过XHR接收网页的一部分,然后使用。在此之后,我更改了一些元素,但是我无法将文档附加到iFrame 解析的文档没有问题,但是当通过调用iFrame.contentDocument=parsedDocument将此文档附加到iFrame时,iFrame.contentDocument保持为空(实际上有html、head和body标记,但它们的内容为空) 我正在解析接收到的数据,如下所示: var parser = new DOMParser(); var parsedDocument= p
iFrame.contentDocument=parsedDocument
将此文档附加到iFrame时,iFrame.contentDocument
保持为空(实际上有html、head和body标记,但它们的内容为空)
我正在解析接收到的数据,如下所示:
var parser = new DOMParser();
var parsedDocument= parser.parseFromString(xhr.response, 'text/html');
我的期望是这样做:
iFrame.contentDocument = parsedDocument;
正如Epasarello在评论中所说,以下措施将起作用:
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);
doc.write(“”+newHTML);
因为document.documentElement.outerHTML
将不包含doctype。如果您对其进行写入var doc=document.getElementById('iframeId').contentWindow.document;doc.open();文件写入(解析文件);doc.close()
@epascarello它现在在iFrame中显示[object HTMLDocument]
。@MarijnS95您应该尝试xhr.response
,而不是parsedDocument
parsedDocument
是一个HTMLDocument
对象,而您希望改为写入实际字符串,否则它将尝试写入HTMLDocument.toString()
,它将返回[object HTMLDocument]
.Duh,就我而言,因为它是一个对象…你必须拉出html字符串…@joetje50但我该如何管理元素的更改呢?