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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…