Best solution to avoid xss while using render to create dom element in a column
Best solution to avoid xss while using render to create dom element in a column
Hello,
I realized i have xss in my datatable, while using column.render to generate an anchor with unsafe data input.
I want to generate an anchor in a cell, having a link name based on an unsafe data.
actually, my render function is :
render : function(data, type, row) {
return "<a href=\""+row.link+"\" title=\""+data+"\">"+data+"</a>";
}
But as mentionned, data is unsafe, and can be "alert('xss');", so the previous function generate an xss.
I don't really know what is the best pratice as I really need to generate an anchor.
I thought first to create an anchor with jquery, and setting the title and name with the text() function, but then i don't know how to inject this dom element into the cell, because render function return a string :
render : function(data, type, row) {
var linkToRes= $(<a></a>);
linkToRes.attr({ title : data });
linkToRes.attr({ href: row.link});
linkToRes.text(data);//prevent xss
return linkToRes;//KO display [Object object]
}
,
what i finally did is escape manually the data input befor generating the anchor (but i'm not sure it's a good practise):
render : function(data, type, row) {
return "<a href=\""+row.link+"\" title=\""+sanitize(data)+"\">"+sanitize(data)+"</a>";
}
Any ideas?
Thanks for your help
Answers
return linkToRes.outerHTML;
should do it.This is a limitation of the
render
callback though in that it can't return DOM elements for display - that is something that will be addressed in future.For now, try the outerHTML option, or encode the data part, stripping out or replacing any unsafe characters (e.g.
<
,>
and&
).Allan