微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript 将文档保存为 .html

如何解决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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。