以编程方式打开“查看源”使用Javascript在浏览器中的HTML窗口? [英] Programmatically open "View Source" HTML Window in Browser with Javascript?

查看:132
本文介绍了以编程方式打开“查看源”使用Javascript在浏览器中的HTML窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I programmatically open the "View Source" window (using some Javascript) like when I right click in the browser and click "View Source"? Is this possible?

推荐答案

你可以使用这个脚本,我们只需抓取html标签的innerHTML,重新加载,然后粘贴在弹出窗口中。

You could use this script, we simply grab the innerHTML of the html tag, reappend that, and paste that in a popup.

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

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

This will not completely show the source as it will not show anything outside the HTML tags, or any properties inside the html tag, but it should be close enough, and works cross-browser.

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

The advantage of this solution over the view-source: solution is that it will also work in internet-explorer 6> on windows XP SP2, that's pretty much it. If none of your audience is in this group, go with the view-source option, its way simpler.

这篇关于以编程方式打开“查看源”使用Javascript在浏览器中的HTML窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆