简体   繁体   English

javascript页面源帮助

[英]javascript page source help

当前,我正在为一个用户编写一个系统,该系统在填写表单时会为HTML电子邮件创建一个模板,该模板将可与他们的CRM系统一起使用,问题是您的用户有点服从,并且对他们的生活不屑一顾。无法理解如何查看页面的源代码,因此他们可以将模板代码复制并粘贴到其CRM中,我想要的是能够有一个链接/按钮,用户可以单击该链接/按钮以在页面中显示源代码。窗口,我现在是一名JavaScript开发人员,因此任何提示,提示示例都将非常有用。

Well you probably want to do something like this: grab the "innerHTML" of the element containing your template HTML (or whatever it is). 好吧,您可能想要执行以下操作:抓取包含模板HTML(或任何内容)的元素的“ innerHTML”。 Then open a new window and drop the HTML into it, surrounded by a <pre> block. 然后打开一个新窗口,将HTML放入其中,并用<pre>块包围。 You'll also want to replace all the important markup characters with appropriate HTML entities, and probably replace newlines with <br> elements. 您还将需要用适当的HTML实体替换所有重要的标记字符,并可能用<br>元素替换换行符。

It'd probably be close to this (but it's not tested): 它可能与此接近(但未经测试):

var html = document.getElementById('whatever').innerHTML
  .replace(/&/g, '&amp;')
  .replace(/</g, '&lt;')
  .replace(/>/g, '&gt;')
  .replace(/\r?\n/g, '<br>');

var w = window.open('', 'SourceWindow', 'height=500,width=600');
var d = w.document.open();
d.write('<html><body><pre>' + html + '</pre></body></html>');
d.close();

edit — if you want to strip script blocks, you could add this "replace" call to the series above: 编辑 -如果要剥离脚本块,可以将此“替换”调用添加到上述系列中:

.replace(/<\s*script[^>]*>.*?<\/\s*script[^>]*>/g, '')

That's a little shaky because in general trying to recognize HTML with a regular expression is not really possible. 这有点不稳定,因为一般来说,实际上不可能尝试使用正则表达式识别HTML。 However, since script tags don't really contain markup and definitely end with the next closing script tag, it's less odious than the general case. 但是,由于脚本标签实际上并不包含标记,而且肯定以下一个关闭的脚本标签结尾,因此与一般情况相比,它没有那么令人讨厌。

I think the best practice here isn't really to use a Javascript trick, but to copy the HTML template into a visible section and replace "<" with "&lt;", ">" with "&gt;" 我认为此处的最佳做法并不是真正使用Javascript技巧,而是将HTML模板复制到可见部分,然后将“ <”替换为“&lt;”,“>”替换为“&gt;” (escaping other bits as needed). (根据需要转义其他位)。

I would argue that it makes for poor usability to force a user to view the page source themselves, and it's not hard to use regex to make these replacements. 我认为这会迫使用户自己查看页面源,因此可用性很差,并且使用正则表达式进行替换并不难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM