在javascript中过滤转义的尖括号
我有一个 javascript 功能,允许用户在页面上放置任意文本字符串。我不希望他们能够插入 html 或其他代码,而只是纯文本。
所以我认为去掉所有尖括号(<
>
)就可以了。 (我不在乎他们的页面上是否有“损坏”的 html,或者他们无法在文本中放入尖括号)然后我意识到我必须过滤转义的尖括号 (<
>
),可能还有其他。
为了安全起见,我需要过滤掉什么?删除所有尖括号就能解决问题吗?
I have a javascript feature that allows users to place arbitrary text strings on a page. I don't want them to be able to insert html or other code, just plain text.
So I figure that stripping out all angle brackets(<
>
) would do the trick. (I don't care if they have 'broken' html on the page, or that they're not able to put angle brackets in their text) Then I realized I had to filter escaped angle brackets (<
>
) and probably others.
What all do I need to filter out, for security? Will removing all angle brackets do the trick?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需将所有尖括号替换为其转义形式即可。这样,人们可以编写任意数量的“代码”,而它只是显示为纯文本。
Just replace all angle brackets with their escaped form. That way, people can write as much "code" as they like, and it just shows up as plain-text instead.
确保您要做的第一件事是将
&
替换为&
a) 对于 HTML 内容,只需
<
就足够了。b) 对于属性值,例如,如果它在
中,则需要注意双引号,但那就是所有这些都是必要的。不过,同时执行
<
和>
也很好。这取决于上下文。如果您想安全起见,请告诉您的 JavaScript 使用不需要编码的
innerText
,但您可能需要将 css 设置为white-space:pre-wrap
。这不太容易出错,但浏览器兼容性也较差。c) 松散相关的说明是,当使用反斜杠转义 JavaScript 字符串终止符时,如果您将内容放入脚本中,可能会偷偷摸摸地发现,您需要注意
(不区分大小写)您可以转义
或
/
就足够了Make sure that the first thing you do is replace
&
with&
a) For HTML content, just
<
should be enough.b) For attribute values, for example if it is going in
<input name="sendtoserver" value="custom text"/>
you need to take care of double-quotes, but that is all that is necessary. Still it is good to also do<
and>
.It depends on the context. If you want to play it safe, tell your JavaScript to use
innerText
which does not need encoding, but you may want to set the css towhite-space:pre-wrap
. This is less error prone, but also less browser-compatible.c) On a loosely related note, when escaping JavaScript strings terminators using backslashes, The item that might sneak up on you is if you place content in a script, you need to take care of
</script>
(not case sensitive) You can just escape</
or/
should be enough