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?
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:
http://en.wikipedia.org/wiki/View-source
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With