Reputation: 1178
Me and my colleague were having this debate where he states that concatenating strings and variables and using them in jQuery append()
poses no risk in terms of XSS. However, I believe that variables containing untrusted data must be escaped prior to appending the same to the DOM. And default jQuery functions such as text
, attr
, html
, etc do a good job of escaping.
Colleague’s version of the code:
$('#container').append('<div data-someData="' + untrustedData + '">' + untrustedTEXT + '<img src="' + untrustedIMGSRC + '" /></div>');
My version:
/* First append the HTML structure */
$('#container').append('<div><img /></div>');
/* Now assign variables using jQuery functions such as `attr`, `data`, etc */
$('#container div').data('someData', untrustedData);
$('#container div').text(untrustedTEXT);
$('#container div img').attr('src', untrustedIMGSRC);
My version of code increases the code footprint but IMO handles the necessary escaping to prevent XSS. Am I correct in my assumptions or is my colleague correct. Or are we both doing it the wrong way?
Upvotes: 1
Views: 703
Reputation: 14043
jQuery .text()
escapes the contents
jQuery .html()
does not escape the contents
jQuery .append()
and it's relatives do not escape the contents
Upvotes: 2