tl;dr;
Yes, you are correct in your assumption.
Setting innerHTML
is susceptible to XSS attacks if you're adding untrusted code.
(If you're adding your code though, that's less of a problem)
Consider using textContent
if you want to add text that users added, it'll escape it.
What the problem is
innerHTML
sets the HTML content of a DOM node. When you set the content of a DOM node to an arbitrary string, you're vulnerable to XSS if you accept user input.
For example, if you set the innerHTML
of a node based on the input of a user from a GET
parameter. "User A" can send "User B" a version of your page with the HTML saying "steal the user's data and send it to me via AJAX".
See this question here for more information.
What can I do to mitigate it?
What you might want to consider if you're setting the HTML of nodes is:
- Using a templating engine like Mustache which has escaping capabilities. (It'll escape HTML by default)
- Using
textContent
to set the text of nodes manually
- Not accepting arbitrary input from users into text fields, sanitizing the data yourself.
See this question on more general approaches to prevent XSS.
Code injection is a problem. You don't want to be on the receiving end.
The Elephant in the room
That's not the only problem with innerHTML
and eval
. When you're changing the innerHTML
of a DOM node, you're destroying its content nodes and creating new ones instead. When you're calling eval
you're invoking the compiler.
While the main issue here is clearly un-trusted code and you said performance is less of an issue, I still feel that I must mention that the two are extremely slow to their alternatives.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…