3

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

2
  • Possible duplicate of File URL "Not allowed to load local resource" in the Internet Browser Commented Jan 30, 2017 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? Commented Jan 30, 2017 at 20:58

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! This is exactly as I wanted.
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.
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");
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.