[英]Do I need to do string sanitation before adding to DOM?
In our team we came up with the idea that we have to do sanitizing of strings before added to the DOM. 在我们的团队中,我们想到了在添加到DOM之前必须对字符串进行清理的想法。 We expected at least that double quotes would be troublesome if used in setAttribute and < and > if added to the node content.
我们至少希望如果在setAttribute中使用双引号以及在添加到节点内容中使用<和>时会造成麻烦。
The first tests showed something different. 最初的测试显示出一些不同之处。 We are using innerHTML to set a nodes content.
我们正在使用innerHTML设置节点内容。 This escapes all unsafe characters by its own.
这会自行转义所有不安全的字符。 But even setAttribute does escape < and >
但是即使setAttribute也会转义<和>
So is this always the case because I couldn't find anything on google? 所以总是这样,因为我在Google上找不到任何东西吗? I don't know if there are browsers out there that would fail.
我不知道是否有浏览器会失败。
innerHTML is editing the HTML inside an element and generating DOM nodes from it - you need write HTML according to the normal rules (eg you can't use a < character unless it is followed by a non-name character). innerHTML正在编辑元素内的HTML并从中生成DOM节点-您需要按照常规规则编写HTML(例如,除非后接非名称字符,否则您不能使用<字符)。 Browsers will perform their usual error recovery though.
浏览器将执行通常的错误恢复。
I don't understand why your experience of innerHTML differs from that. 我不明白为什么您对innerHTML的体验与此不同。
createTextNode, setAttribute, etc edit the DOM directly. createTextNode,setAttribute等直接编辑DOM。 HTML is not involved, so you don't have to deal with characters that have special meaning in HTML.
不涉及HTML,因此您不必处理在HTML中具有特殊含义的字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.