javascripthtmlhyperlinkview-source

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


Solution

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