Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the HTML source from the page?

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?

like image 613
mck89 Avatar asked Sep 02 '09 13:09

mck89


People also ask

How can you view the source HTML code of a Web page on Chrome?

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.”

How do I copy HTML source?

Copy the HTML: Press the CTRL+C shortcut to copy, or right-click on your selected text and click Copy.


2 Answers

Use

document.documentElement.outerHTML 

or

document.documentElement.innerHTML 
like image 66
Eldar Djafarov Avatar answered Sep 25 '22 05:09

Eldar Djafarov


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>
...
like image 28
Paul S. Avatar answered Sep 22 '22 05:09

Paul S.