Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

dom - web console javascript download-save document to .html

In the current opened page, using the web console, save document to .html

or document inside an <iframe>

By document to save in .html, I mean everything inside the <html> (which is enough to render the page), including or not including the (DOCTYPE, <html>)


something like this ?
document.save("name.html")
question from:https://stackoverflow.com/questions/65838243/web-console-javascript-download-save-document-to-html

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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 + '
' : '') + 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
    }
}

if you need to get document inside an iframe:

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

if you want to use new XMLSerializer().serializeToString(document) instead of document.documentElement.outerHTML
read the comments here to see the differences: How to get the entire document HTML as a string?

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...