在javascript中过滤转义的尖括号

发布于 2024-12-10 07:38:58 字数 290 浏览 0 评论 0原文

我有一个 javascript 功能,允许用户在页面上放置任意文本字符串。我不希望他们能够插入 html 或其他代码,而只是纯文本。

所以我认为去掉所有尖括号(< >)就可以了。 (我不在乎他们的页面上是否有“损坏”的 html,或者他们无法在文本中放入尖括号)然后我意识到我必须过滤转义的尖括号 (&lt; &gt;),可能还有其他。

为了安全起见,我需要过滤掉什么?删除所有尖括号就能解决问题吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

自在安然 2024-12-17 07:38:58

删除所有尖括号就能解决问题吗?

只需将所有尖括号替换为其转义形式即可。这样,人们可以编写任意数量的“代码”,而它只是显示为纯文本。

Will removing all angle brackets do the trick?

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.

喵星人汪星人 2024-12-17 07:38:58

确保您要做的第一件事是将 & 替换为 &

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 to white-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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文