Is there a way to access the page HTML source code using javascript?
I know that I can use document.body.innerHTML
but it contains only the code inside the body. I want to get all the page source code including head and body tags with their content, and, if it's possible, also the html tag and the doctype.
Is it possible?
Chrome: CTRL + U. Or you can click on the weird-looking key with three horizontal lines in the upper right hand corner. Then click on “Tools” and select “View Source.”
Copy the HTML: Press the CTRL+C shortcut to copy, or right-click on your selected text and click Copy.
Use
document.documentElement.outerHTML
or
document.documentElement.innerHTML
This can be done in a one-liner using XMLSerializer.
var generatedSource = new XMLSerializer().serializeToString(document);
Which gives String
<!DOCTYPE html><html><head>
<title>html - javascript page source code - Stack Overflow</title>
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With