2

I'm trying to add a link or button to my site where the user can see the source of the current page.

No luck when tried the following:

<a href="view-source:http://www.example.com" target="_blank">View Source</a>

Any other idea? Maybe with javascript we can get the source from the current page?

Thank you

Moses Davidowitz
  • 958
  • 11
  • 24
Moe E.
  • 31
  • 1
  • 5
  • Possible duplicate of [File URL "Not allowed to load local resource" in the Internet Browser](http://stackoverflow.com/questions/34901523/file-url-not-allowed-to-load-local-resource-in-the-internet-browser) – driconmax Jan 30 '17 at 20:48
  • Are you looking for the original source when the page was initially loaded, or the current state, which may be dramatically different, depending on what kind of javascript has run? – Joe Enos Jan 30 '17 at 20:58

2 Answers2

2

You can add a simple button as follows:

<button type ="button" onclick="viewSource()">View Source</button>

And then the following javascript function:

function viewSource(){;
    var source = "<html>";
    source += document.getElementsByTagName('html')[0].innerHTML;
    source += "</html>";
    source = source.replace(/</g, "&lt;").replace(/>/g, "&gt;");
    source = "<pre>"+source+"</pre>";
    sourceWindow = window.open('','Source of page','height=800,width=800,scrollbars=1,resizable=1');
    sourceWindow.document.write(source);
    sourceWindow.document.close(); 
    if(window.focus) sourceWindow.focus();
}  

This will open it's own window and display the source of the current page.

Moses Davidowitz
  • 958
  • 11
  • 24
  • Thank you! This is exactly as I wanted. – Moe E. Jan 30 '17 at 21:05
  • FYI: This does not format things exactly as originally done, will show the current state of the page as opposed to the original state, and doesn't handle the DOCTYPE header or attributes on the `html` element. Keep that in mind when you use it. – Joe Enos Jan 30 '17 at 21:32
1

Check this link

Here there is a nice example of creating View Source button

Html:

<a href="#source-code">View Source</a>
<div id="#source-code"></div>

Css:

#source-code { display: none; }
#source-code:target { display: block; }

Javascript:

var html = $("html").html();
$(function() {
    $("<pre />", {
        "html":   '&lt;!DOCTYPE html>\n&lt;html>\n' + 
                $("html")
                    .html()
                    .replace(/[<>]/g, function(m) { return {'<':'&lt;','>':'&gt;'}[m]})
                    .replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi,'<a href="$1">$1</a>') + 
                '\n&lt;/html>'
    }).appendTo("#source-code");
});
Ashkan Mobayen Khiabani
  • 30,915
  • 26
  • 90
  • 147