I have a piece of JavaScript string, coming from an untrusted source, embedded inside of an onclick tag and I'm not sure what the correct way of encoding this string is. Here is a simplification of the HTML:
<input type="button" onclick="alert([ENCODED STRING HERE]);"
value="Click me" />
I use the Microsoft AntiXss library which contains several methods to encode with. The text is embedded in a HTML / XML attribute, so XML attribute encoding, using the AntiXss.XmlAttributeEncode method seems appropriate. However, it is also a piece of JavaScript. Therefore JavaScript encoding using the the AntiXss.JavascriptEncode method seems appropriate too.
Which one should I choose in such a way that I don’t expose a security leak, while allowing the text to be displayed correctly?
UPDATE: The workaround I currently use is by using
XmlAttributeEncode
on this text and put this inside a custom attribute in the tag. After that I use some JavaScript to read it from this tag. It basically looks like this:
<input type="button" onclick="alert(this.getAttribute('comment');"
value="Click me" comment="[XML ATTRIBUTE ENCODED TEXT HERE]" />
While this works perfectly and solves the problem, I'm still very curious about how to correctly encode JavaScript inside an XML attribute.