jQuery .text()方法XSS安全吗? [英] Is jQuery .text() method XSS safe?
问题描述
我有来自用户的未转义数据。
I have unescaped data from users.
这样使用是安全的:
var data = '<test>a&f"#</test>'; // example data from ajax response
if (typeof(data) === 'string')
$('body').text(data);
我可以这样使用,还是有一些问题,如编码或一些特定的符号,我应该小心并添加更严格的验证?
Can I use like this or there is some problems like encoding or some specific symbols that I should be careful and add more strict validation?
推荐答案
当您使用<设置元素的文本时code> text 方法,jQuery在内部使用 createTextNode
,它会转义所有特殊字符。
When you set the text of an element using the text
method, jQuery uses createTextNode
internally, which escapes all special characters.
来自 jQuery docs :
我们需要知道这个方法转义必需的
提供的字符串,以便在HTML中正确呈现。为此,它调用
DOM方法.createTextNode()
,它取代了特殊的cha racters
及其HTML实体等价物(例如& lt;
<
)
We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method
.createTextNode()
, which replaces special characters with their HTML entity equivalents (such as<
for<
)
所以是的,它应该是安全的。这是你在jsfiddle中的例子。注意标签如何显示为文字文本。
So yes, it should be safe. Here's your example in jsfiddle. Notice how the tags appear as literal text.
这篇关于jQuery .text()方法XSS安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!