JavaScript Basic Stuff - Page's HTML View-Source Programmatically

Posted at

There are 2 options   [ and a workaround, which I will Explain later.. ]



#1. "HTML" From D.O.M


//get HTML from DOM (not really HTML from the server but an interrupted one - the plus is that it is immediate to fetch).
(function(){
"use strict";

var d = document.createElement("div");
d
.style.cssText = "max-width:500px; max-height:200px; background-color:rgba(223,223,223,.7); border:3px solid rgba(0,0,0,.5); padding:5px; margin:10px; overflow-x:hidden; overflow-y:auto; word-break:break-word; font-family:'Courier New',Consolas,Lucida Console,monospace,sans-serif; text-shadow:.3px .3px rgba(0,0,0,.2),-0.3px -0.3px rgba(0,0,0,.2); border-radius:5px; box-shadow:1px 1px 5px rgba(0,0,0,.3),-1px -1px 5px rgba(0,0,0,.3)";
d
.appendChild(document.createTextNode(document.querySelector('html').innerHTML));
document
.querySelector('body').appendChild(d);
}());

this is the 'safe' result, without the <html> wrapping and doctype: from DOM

#2. HTML From Server (Through "Self-Ajax")


//get HTML from server, its the real-deal, but requires internet-connection (again...), since its the same-page you are OK to Ajax (domain wise..)
(function(){
var xhr = new XMLHttpRequest();
xhr
.responseType = "text";
xhr
.onreadystatechange = function(e){
var
xhr
= e.target
, d = document.createElement("div")
;

if(xhr.DONE !== xhr.readyState) return;

d
.style.cssText = "max-width:500px; max-height:200px; background-color:rgba(223,223,223,.7); border:3px solid rgba(0,0,0,.5); padding:5px; margin:10px; overflow-x:hidden; overflow-y:auto; word-break:break-word; font-family:'Courier New',Consolas,Lucida Console,monospace,sans-serif; text-shadow:.3px .3px rgba(0,0,0,.2),-0.3px -0.3px rgba(0,0,0,.2); border-radius:5px; box-shadow:1px 1px 5px rgba(0,0,0,.3),-1px -1px 5px rgba(0,0,0,.3)";

d
.appendChild(document.createTextNode(xhr.responseText));
document
.querySelector('body').appendChild(d);
}
xhr
.open("GET", String(window.location.href), true);
xhr
.send();
}());

I've ran both in the console, in this current page (naturally before I've wrote this answer..)


and this is the side by side result, notice the difference.

Side By Side

notes and stuff..:

 

my answer available here:
http://stackoverflow.com/a/29131388/257319