Suppose you've made a demo(a webpage) of your product, you want to make a page to display the demo, and in the bottom of the page, there is a button by click which you can display the source code of the demo above. How to do this job nicely?
-
1Just the html/css/javascript, or the server-side code as well? – Zirak Aug 30 '11 at 09:16
2 Answers
The following should work at least in Firefox (via XMLSerializer), Internet Explorer, Chrome and Safari (via outerHTML). In browsers that support neither it will fall back to innerHTML
with the disadvantage being that the root element itself (<html>
) isn't included.
function getMyCode()
{
if ("XMLSerializer" in window)
return new XMLSerializer().serializeToString(document.documentElement);
else if ("outerHTML" in document.documentElement)
return document.documentElement.outerHTML;
else
return document.documentElement.innerHTML;
}
Then again, if you want the "real" source code rather than the serialized version of the DOM you won't get around downloading it again - the browser doesn't necessarily store it. You can use XMLHttpRequest:
function getMyCode()
{
var req = new XMLHttpRequest();
req.open("GET", window.location.href);
req.onreadystatechange = function()
{
if (this.readyState != 4)
return;
alert(this.responseText);
};
req.send(null);
}

- 56,865
- 12
- 98
- 126
-
I want the source code(what you see use right-click-view-page-source), but IIRC the innerHTML is the DOM(what you see with Chrome developer tools) – wong2 Aug 30 '11 at 09:25
Make the request to the same page and ensure that the server responds with Content-Type set to "text/plain" instead of "text/html". If it is a server side script, then you can use query parameters to determine when to set Content-Type to "text/html" or "text/plain". If it is a static web page, you can make different URIs with different content types.

- 11,241
- 9
- 44
- 54