【问题标题】:Add option to view source of current HTML page添加选项以查看当前 HTML 页面的源代码
【发布时间】:2017-06-16 03:39:47
【问题描述】:

我正在尝试向我的网站添加一个链接或按钮,用户可以在其中看到当前页面的来源。

尝试以下方法时运气不佳:

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

还有什么想法吗?也许使用javascript我们可以从当前页面获取源代码?

谢谢

【问题讨论】:

标签: javascript html hyperlink view-source


【解决方案1】:

你可以添加一个简单的按钮如下:

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

然后是下面的javascript函数:

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();
}  

这将打开它自己的窗口并显示当前页面的源代码。

【讨论】:

  • 谢谢!这正是我想要的。
  • 仅供参考:这与最初所做的格式不完全相同,将显示页面的当前状态而不是原始状态,并且不处理 DOCTYPE 标题或 html 上的属性元素。使用时请记住这一点。
【解决方案2】:

查看this link

这里有一个创建查看源按钮的好例子

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");
});

【讨论】:

    猜你喜欢
    • 2010-12-20
    • 2013-12-03
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 2014-09-21
    相关资源
    最近更新 更多