How do I obtain the current page's source using JavaScript
and DOM
?
Would I have to use AJAX
?
Asked
Active
Viewed 1,803 times
3
-
1By "a" page, do you mean the current page, or a remote one ? – ldiqual Jun 16 '12 at 12:37
-
What page's source? We need more information captain! – epascarello Jun 16 '12 at 12:37
-
3Do you want the source of the currently **rendered** page, or the source of the page that was **fetched**? It's not necessarily the same thing. – haylem Jun 16 '12 at 12:43
-
Just the fetched page would do. – swatkat Jun 16 '12 at 12:55
2 Answers
4
The current page's source:
document.documentElement.outerHTML
Obviously, that is what the page looks like right now. In case of DHTML, if you want to get the unmodified source as it was served from the server, you will need to make an AJAX call to receive it again, and capture it there.
EDIT: was incorrectly innerHTML
.

Amadan
- 191,408
- 23
- 240
- 301
4
For the current page's HTML, as rendered:
document.documentElement.outerHTML
Alternatively, you could use innerHTML
, but you'd only get the content of the <body>
tag.
For the current page's HTML, as retrieved on page load:
Re-query the page dynamically with an AJAX call.
Using jQuery (easy path):
Any other modern JavaScript library would allow to do something similar, but for the sake of example, with jQuery it would be:
$.ajax(window.location.href, {
success: function (data) {
console.log(data);
}
});
Using the XMLHttpRequest object (more involved):
Obviously going down the bare-bone route, you'll need to handle a few more things yourself, including cross-browser support, but the gist of it would be:
var request = new XMLHttpRequest();
request.open('GET', window.location.href, false);
request.send();
if (request.status === 200) {
console.log(request.responseText);
}

haylem
- 22,460
- 3
- 67
- 96
-
We're both half-right and half-wrong :p `innerHTML` gives you `......`, with a missing `html` element. I'll edit my answer accordingly :D – Amadan Jun 16 '12 at 12:59