Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery append without HTML?

Tags:

jquery

append

xss

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

like image 535
SSpoke Avatar asked Sep 15 '25 04:09

SSpoke


2 Answers

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.

like image 137
Nick Craver Avatar answered Sep 16 '25 19:09

Nick Craver


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);
like image 21
Fabian Avatar answered Sep 16 '25 18:09

Fabian