JQuery append without HTML?
Hello I'm having XSS Vulnerability using jQuery's .append() function
what I'm doing is appending raw chat messages coming from users and I don't want to strip html tags serversided or clientsided I just want to display them. Yet jquery's .append() method renders the html markup.
anyway to do like appendText()? I tried .text() but it doesn't work properly generating the proper html.
I currently use.
var li = $('<div></div>').addClass('chatmsg');
var al = $('<span></span>'开发者_运维百科).addClass(chatClass).text("You");
li.append(al);
li.append(" " + msg);
$('.chat').append(li);
How can I fix the li.append(" " + msg);
line to ignore rendering html thank you, without anything advanced like regular expressions and such.
Thanks
You can change it just a bit, like this:
var li = $('<div />', { text: ' ' + msg, 'class': 'chatmsg' });
var al = $('<span />', { text: 'You', 'class': chatClass });
li.prepend(al);
$('.chat').append(li);
This is calling .text()
under the covers, encoding anything that might be in msg
.
You can use the following function:
function htmlEncode(value){
return $('<div/>').text(value).html();
}
So your code becomes:
var li = $('<div></div>').addClass('chatmsg');
var al = $('<span></span>').addClass(chatClass).text("You");
li.append(al);
li.append(" " + htmlEncode(msg));
$('.chat').append(li);
精彩评论