12

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?

Peter van der Does
  • 12,574
  • 3
  • 34
  • 42
Lance Pollard
  • 66,757
  • 77
  • 237
  • 416

7 Answers7

25

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

richardtallent
  • 32,451
  • 13
  • 78
  • 116
15

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.

Pim Jager
  • 30,915
  • 16
  • 70
  • 97
  • Excellent workaround. One more replacement is needed, for ampersands, so escaped entities are rendered in source. IIRC (and this is a vague recollection), some browsers may not give you exactly the same source with innerHTML (losing original white space, altering some capitalization of elements/attributes, etc.), but it's close enough for most purposes. – richardtallent Nov 30 '09 at 00:39
  • 1
    Why not simply use `outerHTML`? – Bergi Mar 18 '15 at 19:50
3

This will do it for broswers supporting the view-source: schema

javascript:void(window.open('view-source:'+location.href))

A bookmarklet to do this can be made from the link in this scURIple:

data:text/html;charset=utf-8,<html>
       <a href="javascript:void(window.open('view-source:'+location.href))">view-source</a>
</html>

Such a bookmarklet can be used on any page with a URI of an arbitrary schema and not just http: or pages that are HTML based (and hence devoid of properties like .innerHTML).

Thus the URI for (these scURIples are amenable to immediate mode rendering):

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABnElEQVQ4jWNgwAMaGBiYHqdqT36SpvP/carOgdueKuz41OM2JE177ZM0nf+PUrUXkmwAAwMDw91QJf7HKTqnn6Tp/H+UplNNUMOrqaw5r6ew1D2fxCAKE3uYpKv0OEX3KdQlETg1P+5j4Hw9he3q66ls/19NZX35agpLzcsJDOIMDAwMj5O1zR6n6P54nKb942GqpgtWAxoaGJheTWVQeTeNqe31VJbPUINev5rB0ny/gUHgSbaqz5Mk/T+Pk3UbCXrlQT+D5NupTE3vpjG9fTOV9f+racxvXvZzND0tk/JrYGBgwtCwqtCSc3WFQ/GqEqfAZYWO2vMTFDgYGBgYrjaI8jybyFn0bhrTo3fTmf6/mc4gjdXGVcW2WmsrHP/D8OpypzcrS10OrC53bN1QaRVypFkj6FaPSCROJ88sd+FfV2YdtKHCrmV9he3ODeW29zZU2P1fX2H/f2254//VZU7/VxY72WFozM3J+Z+bk/Mfq6HFviJzy31tFld4payscJ44s8BdEkM9sgCMjQtjtZCqBhADcBpAKqaKAQB1iiloT36niAAAAABJRU5ErkJggg==

can be examined directly with:

view-source:data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABnElEQVQ4jWNgwAMaGBiYHqdqT36SpvP/carOgdueKuz41OM2JE177ZM0nf+PUrUXkmwAAwMDw91QJf7HKTqnn6Tp/H+UplNNUMOrqaw5r6ew1D2fxCAKE3uYpKv0OEX3KdQlETg1P+5j4Hw9he3q66ls/19NZX35agpLzcsJDOIMDAwMj5O1zR6n6P54nKb942GqpgtWAxoaGJheTWVQeTeNqe31VJbPUINev5rB0ny/gUHgSbaqz5Mk/T+Pk3UbCXrlQT+D5NupTE3vpjG9fTOV9f+racxvXvZzND0tk/JrYGBgwtCwqtCSc3WFQ/GqEqfAZYWO2vMTFDgYGBgYrjaI8jybyFn0bhrTo3fTmf6/mc4gjdXGVcW2WmsrHP/D8OpypzcrS10OrC53bN1QaRVypFkj6FaPSCROJ88sd+FfV2YdtKHCrmV9he3ODeW29zZU2P1fX2H/f2254//VZU7/VxY72WFozM3J+Z+bk/Mfq6HFviJzy31tFld4payscJ44s8BdEkM9sgCMjQtjtZCqBhADcBpAKqaKAQB1iiloT36niAAAAABJRU5ErkJggg==

---------------------------------------------------------------------

Note: Making the above bookmarklet is an oxymoron and redundant since generally, browsers that support the view-source: schema (protocol) implement it directly in the user interface - however some interfaces are severely crippled which is why this bookmark is especially necessary when using:

window.navigator.userAgent=
         Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4
                                                                                    (Splashtop-v1.2.17.0)

The Splashtop "Instant On" (not) environment by Device VM seriously amputates FF.

(hint: bookmark

   <a href="javascript:void(window.open('view-source:file:///'))">
         use view-source to traverse and peruse Splashtop system files</a>

to browse the Splashtop directory structure, generally ie: view-source:file://media/)

---------------------------------------------------------------------

the devil made me do it - can't resist expounding upon:

... this link (sic view-source:) can be used on any page with a URI of an arbitrary schema ...

including itself, observe the URI:

view-source:view-source:view-source:view-source:view-source:about:blank

produces an obvious HTML source and so has an .innerHTML property

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
                                                                 <html><head><title></title></head><body></body></html>

but

view-source:view-source:view-source:view-source:view-source:about:logo

is not an HTML source and so does not have an .innerHTML property.

As for

a URI of an arbitrary schema:

 view-source:jar:,   view-source:chrome:,   view-source:place:,  ... ?

Presumably, this is elementarily so - as long as the browser can render a page with a URI with a particular schema then that page must have an interpretable source that can be shown, ergo viewable, w/o an interpreted rendering.

(ie. view-source:place:... does not produce any viable page but then neither does a place:... URI though such a URI can be bookmarked - at least with FF [ v.>3.04? ] )

so ...

<a href='view-source:javascript:with(document){write(42);close();}' >v-s:js: answer</a>  
<a href=                    'javascript:with(document){write(42);close();}' >js: question</a>
ekim
  • 31
  • 2
  • 2
    This no longer works. You now get an access denied error if you try to go to a `view-source:` link. – Tot Zam Jun 27 '17 at 17:41
2

One solution, depending on your usage, is to do it as a Firefox add-on or similar.

stpe
  • 3,491
  • 3
  • 29
  • 37
2

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..:

  • you might use the html's outerHTML (but its not always available in every standard DOM)
  • ease up your server's load by compiling/rendering the page's source dynamically in client-side using mustache or handlebars.
  • you can store the text of the page, before any (most) of the modifications in the localStorage, fork the code above, and make a small (and wonderful) script, place this script in the page's head just before you start modifying the page's source..
1

The Simplest Thing To Do Is Use This 1 Line Of Javascript:

//function showSource() {

window.location = "view-source:" + window.location;

//}

I Hope Its Compatible With Your Browser!

  • 5
    This no longer works. You now get an access denied error if you try to go to a `view-source:` link. – Tot Zam Jun 27 '17 at 17:42
-1

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.