HTML: <textarea>-Tag: 如何正确转义显示在那里的 HTML 和 JavaScript 内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2502360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:32:55  来源:igfitidea点击:

HTML: <textarea>-Tag: How to correctly escape HTML and JavaScript content displayed in there?

htmltextarea

提问by jens

I have a HTML Tag <textarea>$FOO</textarea>and the $FOOVariable will be filled with arbitrary HTML and JavaScript Content, to be displayed and edited within the textarea. What kind of "escaping" do I neet to apply to $FOO?

我有一个 HTML 标签<textarea>$FOO</textarea>$FOO变量将填充任意 HTML 和 JavaScript 内容,以在文本区域内显示和编辑。我需要向 $FOO 申请什么样的“逃避”?

I first tought of escaping it HTML but this didnt work (as I will then get shown not the original HTML Code of $FOO but rather the escaped content. This is of course not what I want: I want to be displayed the unescaped HTML/JS Content of the variable...

我首先尝试转义 HTML,但这不起作用(因为我将不会显示 $FOO 的原始 HTML 代码,而是显示转义的内容。这当然不是我想要的:我想显示未转义的 HTML/ JS 变量的内容...

Is it impossible to display HTML Content within a <textarea>tag and also allow it to be editable as full HTML?

是否不可能在<textarea>标签中显示 HTML 内容并允许将其作为完整的 HTML 进行编辑?

thanks jens

谢谢詹斯

回答by bobince

I first tought of escaping it HTML

我第一次尝试转义 HTML

Yes, that's right. The contents of a <textarea>are no different from the contents of any other element like a <span>or a <p>: if you want to put some text inside you must HTML-escape any <or &characters in it to &lt;and &amp;respectively.

恩,那就对了。的内容<textarea>是从没有像其他任何元素的内容不同<span>或者<p>:如果你想放一些文本中必须HTML转义任何<&在它的字符&lt;&amp;分别。

Browsers do tend to give you more leeway with fault markup in <textarea>?s, in that the fallback for invalid unescaped <symbols is to render them as text instead of tags, but that doesn't make it any less wrong or dangerous (for XSS).

浏览器确实倾向于在<textarea>?s 中为您提供更多的错误标记余地,因为无效的未转义<符号的后备是将它们呈现为文本而不是标签,但这并没有减少它的错误或危险(对于 XSS)。

but this didnt work

但这没有用

Please post what you did that didn't work. HTML-escaping is definitely the right thing.

请发布您所做的没有奏效的事情。HTML 转义绝对是正确的。

回答by Gumbo

You need to replace the special character of HTML with character references(either numerical character references or entity references), in textarea, at least &, <and >.

您需要,以取代HTML的特殊字符的字符引用(无论是数字字符引用或实体引用),中textarea,至少&<>