Sanitizing user input before adding it to the DOM in Javascript
Posted
by I GIVE TERRIBLE ADVICE
on Stack Overflow
See other posts from Stack Overflow
or by I GIVE TERRIBLE ADVICE
Published on 2010-05-08T12:59:11Z
Indexed on
2010/05/08
13:28 UTC
Read the original article
Hit count: 138
I'm writing the JS for a chat application I'm working on in my free time, and I need to have HTML identifiers that change according to user submitted data. This is usually something conceptually shaky enough that I would not even attempt it, but I don't see myself having much of a choice this time. What I need to do then is to escape the HTML id to make sure it won't allow for XSS or breaking HTML.
Here's the code:
var user_id = escape(id)
var txt = '<div class="chut">'+
'<div class="log" id="chut_'+user_id+'"></div>'+
'<textarea id="chut_'+user_id+'_msg"></textarea>'+
'<label for="chut_'+user_id+'_to">To:</label>'+
'<input type="text" id="chut_'+user_id+'_to" value='+user_id+' readonly="readonly" />'+
'<input type="submit" id="chut_'+user_id+'_send" value="Message"/>'+
'</div>';
What would be the best way to escape id
to avoid any kind of problem mentioned above? As you can see, right now I'm using the built-in escape()
function, but I'm not sure of how good this is supposed to be compared to other alternatives. I'm mostly used to sanitizing input before it goes in a text node, not an id itself.
© Stack Overflow or respective owner