Here's XSS filtering JavaScript code
var XSSfilter = function( content ) {
return content.replace(/</g, "<").replace(/>/g, ">");};
and append source below
function send_msg(nick, msg) {
var html = '<div class="msg_box"><img class="profile-pic" src="http://i.imgur.com/.jpg">
<div class="user_name_chat">{NAME}</div>
<div class="text">{MESSAGE}</div><div class="clear"></div>';
var append = html.replace('{NAME}', nick);
html = append.replace('{MESSAGE}', msg);
console.log(html);
$('#messages').append(XSSFilter(html));}
When I append this, it doesn't append <b>HTML</b>
, it appends <b>string</b>
instead.
What I want : img+nick+msg
result : <div class="msg_box" ....
Any solutions about this problem?
First, Uncaught ReferenceError: XSSFilter is not defined
. You need to make sure the function name matches your call. Either change the function name to XSSFilter
or call it with XSSfilter
- I would assume the former.
Okay, now beyond that. When you use console.log
it is going to actually call toString()
on the argument. The result is that you don't see your regex is actually converting the <div>
to <div>
which is not valid html and as a result is appended as a string by jQuery.
The best approach would be to only filter the part that is being input (the nick and the message).
var XSSFilter = function( content ) {
return content.replace(/</g, "<").replace(/>/g, ">");
};
function send_msg(nick, msg) {
nick = XSSFilter(nick);
msg = XSSFilter(msg);
var html = '<div class="msg_box"><img class="profile-pic" src="http://i.imgur.com/.jpg"><div class="user_name_chat">{NAME}</div><div class="text">{MESSAGE}</div><div class="clear"></div>';
var append = html.replace('{NAME}', nick);
html = append.replace('{MESSAGE}', msg);
console.log(html);
$('#messages').append(html);
}
send_msg('nick','msg');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="messages">
</div>