Skip to content Skip to sidebar Skip to footer

Obtain Current Page's Source Using Javascript And DOM

How do I obtain the current page's source using JavaScript and DOM? Would I have to use AJAX?

Solution 1:

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.


Solution 2:

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);
}

Post a Comment for "Obtain Current Page's Source Using Javascript And DOM"