【问题标题】:Append document to iFrame将文档附加到 iFrame
【发布时间】:2014-07-07 20:55:39
【问题描述】:

我目前正在通过 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;

【问题讨论】:

  • 如果你给它写信呢? var doc = document.getElementById('iframeId').contentWindow.document; doc.open(); doc.write(parsedDocument); doc.close();
  • @epascarello 现在在 iFrame 中显示 [object HTMLDocument]
  • @MarijnS95 你应该试试xhr.response 而不是parsedDocumentparsedDocument 是一个HTMLDocument 对象,而你想写实际的字符串,否则它会尝试写HTMLDocument.toString(),这将返回[object HTMLDocument]
  • 呃,就我而言,因为它是一个对象...您必须拉出 html 字符串...
  • @Joeytje50 但是我将如何管理元素的变化呢?

标签: javascript html iframe xmlhttprequest


【解决方案1】:

就像 epascarello 在 cmets 中所说的那样,以下方法将起作用:

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

您可能还想在此处指定一个文档类型,方法是将doc.write(newHTML); 行替换为:

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

因为document.documentElement.outerHTML 不会包含文档类型。

【讨论】:

    猜你喜欢
    • 2013-08-09
    • 2011-07-16
    • 2013-06-03
    • 2010-10-27
    • 2011-10-24
    • 2010-11-20
    • 2016-10-05
    • 2011-10-04
    • 2013-10-13
    相关资源
    最近更新 更多