【问题标题】:javascript save document to .htmljavascript 将文档保存到 .html
【发布时间】:2021-01-22 01:44:51
【问题描述】:

我有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")

【问题讨论】:

    标签: javascript dom download save google-chrome-console


    【解决方案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
    在此处阅读 cmets 以查看差异: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

    【讨论】:

      猜你喜欢
      • 2014-09-02
      • 2013-07-16
      • 2014-11-02
      • 2014-10-21
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      • 2018-06-25
      • 1970-01-01
      相关资源
      最近更新 更多