How do I programmatically open the "View Source" window (using some Javascript) like when I right click in the browser and click "View Source"? Is this possible?
views:
459answers:
4One solution, depending on your usage, is to do it as a Firefox add-on or similar.
You could do the following but it won't be the original HTML source: Loop through the DOM and re-create the source by outputting the properties/values of the nodes you find.
It is not an easy task (a huge one in fact), but it is pretty your only option.
Thanks
PS. I think this is what FF is doing, because there is always a subtle difference in the sources.
You can use the "view-source" URI schema, supported by Firefox, Chrome, and older versions of IE.
No JavaScript required, just a normal link to the page you want the user to see in source view:
<a target="_blank" href="view-source:http://www.wikipedia.org/">view Wikipedia's home page HTML source</a>
More info:
You could use this script, we simply grab the innerHTML of the html tag, reappend that, and paste that in a popup.
function showSource(){;
var source = "<html>";
source += document.getElementsByTagName('html')[0].innerHTML;
source += "</html>";
//now we need to escape the html special chars, javascript has escape
//but this does not do what we want
source = source.replace(/</g, "<").replace(/>/g, ">");
//now we add <pre> tags to preserve whitespace
source = "<pre>"+source+"</pre>";
//now open the window and set the source as the content
sourceWindow = window.open('','Source of page','height=800,width=800,scrollbars=1,resizable=1');
sourceWindow.document.write(source);
sourceWindow.document.close(); //close the document for writing, not the window
//give source window focus
if(window.focus) sourceWindow.focus();
}
This will not completely show the source as it will not show anything outside the HTML tags, or any properties inside the html tag, but it should be close enough, and works cross-browser.
The advantage of this solution over the view-source: solution is that it will also work in internet-explorer 6> on windows XP SP2, that's pretty much it. If none of your audience is in this group, go with the view-source option, its way simpler.