Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add option to view source of current HTML page

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

like image 590
Moe E. Avatar asked Feb 01 '26 14:02

Moe E.


2 Answers

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.

like image 79
Moses Davidowitz Avatar answered Feb 03 '26 05:02

Moses Davidowitz


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");
});
like image 45
Ashkan Mobayen Khiabani Avatar answered Feb 03 '26 04:02

Ashkan Mobayen Khiabani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!