Is jQuery .text() method XSS safe?

Vytautas picture Vytautas · Mar 16, 2012 · Viewed 34.7k times · Source

I have unescaped data from users.

So is it safe to use like this:

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?

Answer

James Allardice picture James Allardice · Mar 16, 2012

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 &lt; for <)

So yes, it should be safe. Here's your example in jsfiddle. Notice how the tags appear as literal text.