-1

我有document并且我想要 <html> 中的所有内容(足以呈现页面),
包括或不包括 (<html>DOCTYPE)

document.save("name.html")

或者

saveDocument(document, "name.html")

或 <iframe> 内的文档:这里的 innerDocument 是一个文档

var iframe = document.querySelector("#idOfIframe")
var innerDocument = iframe.contentDocument || iframe.contentWindow.document
saveDocument(innerDocument, "name.html")
4

1 回答 1

-1
downloadString(documentToString(document), document.title + '.html')
function downloadString(string, filename, type) {
    var file = new Blob([string], { type: type })
    if (window.navigator.msSaveOrOpenBlob) // IE10+
        window.navigator.msSaveOrOpenBlob(file, filename)
    else { // Others
        var a = document.createElement("a"),
            url = URL.createObjectURL(file)
        a.href = url
        a.download = filename
        document.body.appendChild(a)
        a.click()
        setTimeout(function () {
            document.body.removeChild(a)
            window.URL.revokeObjectURL(url)
        }, 0)
    }
}
function documentToString(document) {
    let doctype = getDoctype(document)
    return (doctype !== false ? doctype + '\n' : '') + document.documentElement.outerHTML
}
function getDoctype(document) {
    var node = document.doctype
    if (node) {
        var html = "<!DOCTYPE "
            + node.name
            + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '')
            + (!node.publicId && node.systemId ? ' SYSTEM' : '')
            + (node.systemId ? ' "' + node.systemId + '"' : '')
            + '>'
    }
    if (html) {
        return html
    } else {
        return false
    }
}

如果您需要在 iframe 中获取文档:

var iframe = document.querySelector("#idOfIframe")
var innerDocument = iframe.contentDocument || iframe.contentWindow.document
downloadString(documentToString(innerDocument), innerDocument.title + '.html')

如果您想使用new XMLSerializer().serializeToString(document)而不是document.documentElement.outerHTML
阅读此处的注释来查看差异:如何将整个文档 HTML 作为字符串?

downloadString(new XMLSerializer().serializeToString(document), document.title + '.html')

来源:
如何将整个文档 HTML 作为字符串获取?
使用 Javascript JavaScript 获取 HTML 的 DocType 作为字符串
:创建和保存文件

于 2021-01-22T01:44:51.037 回答