使用Javascript以编程方式在浏览器中打开"查看源代码"HTML窗口?

Lan*_*ard 10 javascript view-source

如何以编程方式打开"查看源代码"窗口(使用一些Javascript),就像我在浏览器中右键单击并单击"查看源代码"一样?这可能吗?

ric*_*ent 25

您可以使用Firefox,Chrome和旧版IE支持的"view-source"URI架构.

不需要JavaScript,只是您希望用户在源视图中看到的页面的常规链接:

<a target="_blank" href="view-source:http://www.wikipedia.org/">view Wikipedia's home page HTML source</a>
Run Code Online (Sandbox Code Playgroud)

更多信息:

http://en.wikipedia.org/wiki/View-source

  • 这不再起作用,并被视为安全风险:https://bugzilla.mozilla.org/show_bug.cgi?id = 1172165 (5认同)

Pim*_*ger 13

您可以使用此脚本,我们只需获取html标记的innerHTML,重新插入,并将其粘贴到弹出窗口中.

function showSource(){;
    var source = "<html>";
    source += document.getElementsByTagName('html')[0].innerHTML;
    source += "</html>";
    //now we need to escape the html special chars, javascript has escape
    //but this does not do what we want
    source = source.replace(/</g, "&lt;").replace(/>/g, "&gt;");
    //now we add <pre> tags to preserve whitespace
    source = "<pre>"+source+"</pre>";
    //now open the window and set the source as the content
    sourceWindow = window.open('','Source of page','height=800,width=800,scrollbars=1,resizable=1');
    sourceWindow.document.write(source);
    sourceWindow.document.close(); //close the document for writing, not the window
    //give source window focus
    if(window.focus) sourceWindow.focus();
}  
Run Code Online (Sandbox Code Playgroud)

这不会完全显示源代码,因为它不会显示HTML标记之外的任何内容,也不会显示html标记内的任何属性,但它应该足够接近,并且可以跨浏览器工作.

这个解决方案优于view-source:解决方案的优点是它也适用于Windows XP SP2上的Internet-explorer 6>,这就是它.如果您的观众都不在此群组中,请使用view-source选项,方式更简单.