简体   繁体   English

在添加到DOM之前是否需要进行字符串清洁?

[英]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.

相关问题 我是否需要在DOM上插入像素跟踪? - Do I need insert a pixel tracking on the DOM? 在向DOM添加内容时,我需要等待多长时间(setTimeout)来影响类更改? - How long do I need to wait (setTimeout) to affect a class change when adding something to the DOM? 在添加事件侦听器之前是否需要检查浏览器是否支持某个事件 - Do I need to check if a browser supports a certain event before adding the event listener 如何在将 DOM 元素添加到 HTML 之前对其进行操作? - How do I manipulate a DOM Element before it is even added to the HTML? 如何在DOM元素的内容之前和之后插入空格? - How do I insert a space before and after the content of a DOM element? 我是否需要DOM中的图像才能使用画布合并它们? - Do I need to have images in DOM to merge them using canvas? 使用原型时,是否需要将所有内容包装在DOM负载上? - when working with prototypes do I need to wrap everything on DOM load? 我需要在 DOM 事件回调中使用闭包吗? - Do I need a closure inside a DOM event callback? 我需要删除dom片段还是垃圾收集器会删除它们? - Do i need to delete dom fragments or will the garbage collector remove them? 当DOM更改时,我是否需要清理事件处理程序? - Do I need to cleanup my event handlers when DOM changes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM