Is jQuery .text() method XSS safe?
When you set the text of an element using the text
method, jQuery uses createTextNode
internally, which escapes all special characters.
From the jQuery docs:
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<
)
So yes, it should be safe. Here's your example in jsfiddle. Notice how the tags appear as literal text.
Because XSS attacks rely on being able to insert DOM nodes (<img />
, <script />
) etc, and jQuery.fn.text()
does not support this, it is entirely XSS safe.
As you can see in this basic example, all would-be-HTML tags are encoded as a result of jQuery using createTextNode
internally:
jQuery('div').text('<test>a&f"#</test>');
So that what is actually inserted is more equivilant to;
jQuery('div').html('<test>a&f"#</test>');
You still have to be careful when inserting the result into the DOM - see: Cross-Site Scripting vulnerability with JavaScript and JQuery.
For setting the text of elements, however, text should be XSS safe.