HTML 属性中的引号会破坏布局
我的网站有用户生成的内容。我注意到,如果用户在某些文本中包含引号,然后我在 HTML 属性中显示该文本,则 IE 中的布局会变得混乱。
<a href="link.html" title="user "description" of link">Hello</a>
然而,如果我用 Javascript(原型库)生成了相同的锚点,那么 IE 中的布局就不会被搞砸:
$$('body').first().appendChild(
new Element(
'a', {
title: 'user "description" of link',
href: 'link.html'
}
).update('Hello')
);
为什么会这样呢? JS 和纯 HTML 版本都有相同的预期结果,但只有 JS 不会搞砸 IE。幕后发生了什么?
顺便说一句,我执行 strip_tags() 并清除所有用户输入中的 XSS 攻击,但我不会删除所有 HTML 实体,因为我使用大量表单文本输入框来显示用户生成的文本。表单元素实际上显示 HTML 实体,看起来很丑。
My site has user generated content. I noticed that if the user has quotes in some text and later I displayed that text in an HTML attribute, the layout would get screwed up in IE.
<a href="link.html" title="user "description" of link">Hello</a>
However, if I had generated the same anchor with Javascript (Prototype library), the layout would not be screwed up in IE:
$('body').first().appendChild(
new Element(
'a', {
title: 'user "description" of link',
href: 'link.html'
}
).update('Hello')
);
Why is this so? The JS and the plain HTML versions both have the same intended result, but only the JS doesn't screw up IE. What's happening behind the scenes?
BTW, I do strip_tags() and clean XSS attacks from all user input, but I don't strip all HTML entities because I use a lot of form text input boxes to display back user generated text. Form elements literally display HTML entities, which looks ugly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要转义用户指定的所有输出(使用实体)。 DOM 方法会自动执行此操作。
You need to escape all output that is user-specified (using entities). The DOM-methods do that automatically.
我不知道您如何处理用户生成的内容,但您可以使用替换函数来清理输入,例如
string.replace("\"", "")
I don't know how you are processing the user generated content, but you could use a replace function to clean up the input something like
string.replace("\"", "")
你的问题的答案:“为什么会这样”是因为在你的 JavaScript 示例中用单引号设置了 title 属性。因此用户生成的字符串中的双引号已经被转义。
在您的标签示例中,在标题属性中使用的文本周围的单引号可能是解决渲染问题的一种方法。
但是, 您的 HTML 属性应该用双引号引起来,因此您最好使用实体,正如@elusive 在他的回答中所建议的那样。
The answer to your question: 'Why is it so' is because in your JavaScript example set the title attribute with single quotes. So the double quotes in the user generated string are already escaped.
In you A tag example, single quotes around the text you use in the title attribute may be a way to solve the rendering problem.
However, Your HTML attributes should be in double quotes, so you would be better off using entities, as suggested by @elusive in his answer.