在JS中是否有一种方法可以在HTML标签中获取整个HTML,作为字符串?

document.documentElement.??

当前回答

正确的做法其实是:

webBrowser1。DocumentText

其他回答

我只需要doctype html,应该可以在IE11, Edge和Chrome中正常工作。我使用下面的代码,它工作得很好。

function downloadPage(element, event) {
    var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

    if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) {
        document.execCommand('SaveAs', '1', 'page.html');
        event.preventDefault();
    } else {
        if(isChrome) {
            element.setAttribute('href','data:text/html;charset=UTF-8,'+encodeURIComponent('<!doctype html>' + document.documentElement.outerHTML));
        }
        element.setAttribute('download', 'page.html');
    }
}

在你的锚标签中像这样使用。

<a href="#" onclick="downloadPage(this,event);" download>Download entire page.</a>

例子

function downloadPage(element, event) { var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor); if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) { document.execCommand('SaveAs', '1', 'page.html'); event.preventDefault(); } else { if(isChrome) { element.setAttribute('href','data:text/html;charset=UTF-8,'+encodeURIComponent('<!doctype html>' + document.documentElement.outerHTML)); } element.setAttribute('download', 'page.html'); } } I just need doctype html and should work fine in IE11, Edge and Chrome. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. <p> <a href="#" onclick="downloadPage(this,event);" download><h2>Download entire page.</h2></a></p> <p>Some image here</p> <p><img src="https://placeimg.com/250/150/animals"/></p>

如果你想获取DOCTYPE之外的所有内容,这将有效:

document.getElementsByTagName('html')[0].outerHTML;

如果你想要doctype也可以这样:

new XMLSerializer().serializeToString(document.doctype) + document.getElementsByTagName('html')[0].outerHTML;

我相信document.documentElement.outerHTML应该为您返回该值。

MDN表示,目前支持的浏览器包括Firefox 11、Chrome 0.2、Internet Explorer 4.0、Opera 7、Safari 1.3、Android、Firefox Mobile 11、IE Mobile、Opera Mobile、Safari Mobile等。outerHTML在DOM解析和序列化规范中。

outerHTML属性上的MSDN页面指出IE 5+支持它。Colin的回答链接到W3C quirksmode页面,该页面很好地比较了跨浏览器兼容性(也有其他DOM特性)。

我尝试了各种答案,看看返回了什么。我用的是最新版本的Chrome浏览器。

建议:document.documentElement.innerHTML;返回<head>…身体< / >

Gaby的建议document.getElementsByTagName('html')[0].innerHTML;返回相同。

建议:document.documentElement.outerHTML;返回<html><head>…< /身体> < / html > 这是除了'doctype'以外的所有东西。

您可以使用document.doctype;这将返回一个对象,而不是一个字符串,所以如果你需要为所有文档类型提取字符串的细节,包括HTML5,它在这里描述

我只需要HTML5,所以以下内容足以让我创建整个文档:

alert (' < !DOCTYPE HTML>' + '\n' + document.documentElement.outerHTML);

还可以获取<html>…</html>,最重要的是<!DOCTYPE……>声明,你可以遍历文档。childNodes,将它们转换为字符串:

const html = [...document.childNodes]
    .map(node => nodeToString(node))
    .join('\n') // could use '' instead, but whitespace should not matter.

function nodeToString(node) {
    switch (node.nodeType) {
        case node.ELEMENT_NODE:
            return node.outerHTML
        case node.TEXT_NODE:
            // Text nodes should probably never be encountered, but handling them anyway.
            return node.textContent
        case node.COMMENT_NODE:
            return `<!--${node.textContent}-->`
        case node.DOCUMENT_TYPE_NODE:
            return doctypeToString(node)
        default:
            throw new TypeError(`Unexpected node type: ${node.nodeType}`)
    }
}

我把这段代码作为document-outerhtml发布在npm上。


注意上面的代码依赖于doctypeToString函数;它的实现可以如下所示(下面的代码以doctype-to-string的形式发布在NPM上):

function doctypeToString(doctype) {
    if (doctype === null) {
        return ''
    }
    // Checking with instanceof DocumentType might be neater, but how to get a
    // reference to DocumentType without assuming it to be available globally?
    // To play nice with custom DOM implementations, we resort to duck-typing.
    if (!doctype
        || doctype.nodeType !== doctype.DOCUMENT_TYPE_NODE
        || typeof doctype.name !== 'string'
        || typeof doctype.publicId !== 'string'
        || typeof doctype.systemId !== 'string'
    ) {
        throw new TypeError('Expected a DocumentType')
    }
    const doctypeString = `<!DOCTYPE ${doctype.name}`
        + (doctype.publicId ? ` PUBLIC "${doctype.publicId}"` : '')
        + (doctype.systemId
            ? (doctype.publicId ? `` : ` SYSTEM`) + ` "${doctype.systemId}"`
            : ``)
        + `>`
    return doctypeString
}