我如何以编程方式打开“查看源代码”窗口(使用一些 Javascript),就像我在浏览器中右键单击并单击“查看源代码”一样?这可能吗?
原文由 Lance 发布,翻译遵循 CC BY-SA 4.0 许可协议
我如何以编程方式打开“查看源代码”窗口(使用一些 Javascript),就像我在浏览器中右键单击并单击“查看源代码”一样?这可能吗?
原文由 Lance 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用此脚本,我们只需获取 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, "<").replace(/>/g, ">");
//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 标签内的任何属性,但它应该足够接近,并且可以跨浏览器工作。
这个解决方案相对于 view-source: 解决方案的优势在于它也可以在 Windows XP SP2 上的 internet-explorer 6> 中运行,仅此而已。如果您的观众都不在这个组中,请使用查看源选项,这样更简单。
原文由 Pim Jager 发布,翻译遵循 CC BY-SA 2.5 许可协议
13 回答13k 阅读
7 回答2.1k 阅读
3 回答1.3k 阅读✓ 已解决
6 回答1.2k 阅读✓ 已解决
2 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
6 回答1.1k 阅读
您可以使用 Firefox、Chrome 和旧版 IE 支持的“查看源代码”URI 架构。
不需要 JavaScript,只是您希望用户在源代码视图中看到的页面的普通链接:
更多信息:
http://en.wikipedia.org/wiki/查看源代码