Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically open "View Source" HTML Window in Browser with Javascript?

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?

like image 395
Lance Avatar asked Nov 29 '09 08:11

Lance


2 Answers

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

like image 141
richardtallent Avatar answered Oct 21 '22 04:10

richardtallent


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, "&lt;").replace(/>/g, "&gt;");
    //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.

like image 20
Pim Jager Avatar answered Oct 21 '22 04:10

Pim Jager