javascript 将文档保存为 .html

问题描述

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

document.save("name.html")

saveDocument(document,"name.html")

或者

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

解决方法

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
阅读此处的评论以查看差异:How to get the entire document HTML as a string?

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

来源:
How to get the entire document HTML as a string?
Get DocType of an HTML as string with Javascript
JavaScript: Create and save file

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...