I am working on a project where at some point I want to add the functionality of saving the current webpage as HTML, also in pdf, I am saving page in pdf format by this javascript function window.print()
now I want to save it as HTML, but can't find a way to do this, I hope there would be some function to save as HTML. If you know, let me know, it would be a great help.
Note that you can save the current webpage as Html by a keyboard shortcut Ctrl S, and print the page using the keyboard shortcut Ctrl P.
CodePudding user response:
Use document.querySelector("html").innerHTML
to get all the HTML of an page.
Then you have a variable containing the entire document as a string - we can download it with the following function:
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,'
encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
Also take a look at this SO thread