JQuery add without HTML?

Hello, I have an XSS vulnerability using jQuery.append () function

what I am doing is adding raw chat messages from users, and I don’t want to remove html tags from servers or clients, I just want to display them. However, the jquery.append () method displays html markup.

anyway do appendText ()? I tried .text () but it does not work properly creating the correct html.

I am currently using.

  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 li.append ("" + msg);

to ignore html rendering thanks, without any advanced ones like regular expressions etc.

thank

+3
source share
2 answers

You can change it a bit, for example:

var li = $('<div />', { text: ' ' + msg, 'class': 'chatmsg' });
var al = $('<span />', { text: 'You', 'class': chatClass });
li.prepend(al);
$('.chat').append(li);

.text() , , msg.

+7

:

function htmlEncode(value){ 
  return $('<div/>').text(value).html(); 
}

, :

  var li = $('<div></div>').addClass('chatmsg');
  var al = $('<span></span>').addClass(chatClass).text("You");
  li.append(al);
  li.append(" " + htmlEncode(msg));
  $('.chat').append(li);
+3

Source: https://habr.com/ru/post/1764649/


All Articles