I'm using jQuery to make sure that my users can't execute javascript through my chat app. This is how I append the data that I get from WebSocket server to the users:
obj = JSON.parse(e.data);
$("<li>", {
class: "list-group-item",
text: obj.username + ": " + obj.message
}).prependTo('#chatlog');
This works great, and seems to escape all XSS attacks, but here's my problem. I want to make obj.username
bold, but I have no idea how to go about doing that since everything after text:
becomes text. Very happy for any help on this!
Then you can use another way:-
$("<li>", {
class: "list-group-item",
}).append($('<span>', {
class: 'font-weight-bold',
text: obj.username
})).append($('<span>', {
text: `: ${obj.message}`
})).prependTo('#chatlog');
See the snippet below:-
const obj = {
username: 'John Doe',
message: 'Hi!'
};
$("<li>", {
class: "list-group-item",
}).append($('<span>', {
class: 'font-weight-bold',
text: obj.username
})).append($('<span>', {
text: `: ${obj.message}`
})).prependTo('#chatlog');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<ul class="list-group" id="chatlog"></ul>