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

7

16

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?

Caiman answered 29/11, 2009 at 8:37 Comment(0)
S
27

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

Skep answered 29/11, 2009 at 8:49 Comment(3)
This is a no-brainer, but the best solution. Simple. I knew it had to be easy. tyTurbary
For the record, I tried this and it doesn't work with Chrome 56.Ovida
This does no longer work and is considered a security risk: bugzilla.mozilla.org/show_bug.cgi?id=1172165Fiver
C
16

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.

Carcinogen answered 29/11, 2009 at 10:50 Comment(2)
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.Skep
Why not simply use outerHTML?Lowermost
W
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>
Weatherboard answered 14/4, 2014 at 14:37 Comment(1)
This no longer works. You now get an access denied error if you try to go to a view-source: link.Tonytonya
P
2

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

Pelvic answered 29/11, 2009 at 8:43 Comment(1)
Actually, "using some Javascript" is true in the Firefox add-on case as well.Pelvic
R
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..
Repartition answered 18/3, 2015 at 19:47 Comment(0)
D
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!

Depart answered 11/12, 2014 at 19:20 Comment(1)
This no longer works. You now get an access denied error if you try to go to a view-source: link.Tonytonya
A
-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.

Amersfoort answered 29/11, 2009 at 8:49 Comment(4)
Not the one who downvoted you, but you can always grab innerHTML.Godlike
I was referring to a solution like @Pim Jager said, and the question was about doing it in JavaScript, so I guess I'll downvote the FF add-on solutionAmersfoort
@orip: I'll assume it and learn from it :) in 10 years I've never heard of "view-source:" URI schema!Amersfoort
neither have I, which makes this question great :)Speechless

© 2022 - 2024 — McMap. All rights reserved.