如何将当前页面DOM加载到变量中,然后将其写入使用JavaScript的iframe



我正在使用此处描述的方法(https://stackoverflow.com/a/10433550/556079)来创建一个加载我给它的html而不是从另一个加载的html的iframeURL。我要加载的HTML是当前页面的整个DOM(本质上是镜像)。

这是上面链接的该问题的代码。除了我需要将更多的html纳入iFrame之外,这一切都很好。

var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();

您可以看到,它将<body>Foo</body>加载到iFrame中。我尝试这样做:var html = document;,但这不起作用。

此代码用于镀铬扩展名中,因此我只需要在Chrome中工作。我这样做的理由是我想在iframe中操纵代码。不幸的是,Chrome不允许本地页面互相交谈,而本地页面是我使用此Chrome Extension的位置。

有什么想法?

您可以通过innerHTML(不包括<body></body>)或outerHTML读取当前文档的body的标记。如果您还需要head,则可以在document.head上执行相同的操作。如果两者都需要,则要组合这两个或使用document.documentElement(这是html元素)。如果您需要Doctype,则在document.doctype上(是DocumentType对象):

所以:

var iframe = document.createElement('iframe');
var html = "";
// Reassemble the doctype if there is one
if (document.doctype && document.doctype.name) {
    html = "<!doctype " + document.doctype.name;
    if (document.doctype.publicId) {
        html += " PUBLIC " + document.doctype.publicId;
    }
    if (document.doctype.systemId) {
        html += " " + document.doctype.systemId;
    }
}
// Add in the document's markup
html += document.documentElement.outerHTML;
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();

现在标准化了所有三个(innerHTMLouterHTMLdocument.doctype)。前两个由DOM解析和序列化规范涵盖,该规范是从HTML规格的共同基础结构部分引用的,document.doctype在DOM规范中。

最新更新