-1

I have document and I want everything inside the <html> (which is enough to render the page)
including or not including the (<html> or DOCTYPE)

document.save("name.html")

or

saveDocument(document, "name.html")

or document inside <iframe>: here innerDocument is a document

var iframe = document.querySelector("#idOfIframe")
var innerDocument = iframe.contentDocument || iframe.contentWindow.document
saveDocument(innerDocument, "name.html")
Mr. Doge
  • 796
  • 5
  • 11

1 Answers1

0
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
    }
}

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

Mr. Doge
  • 796
  • 5
  • 11