in general, in javascript, isn't using innerHTML an [in]security issue?

with the DOM and cool new tools such as reactjs, should innerHTML ever be used in a javascript program?

using it is a lot like opening oneself to an SQL injection attack, but here it's a cross-site scripting etc. everything needs to be examined and scrubbed before it's used.

seems to me innerHTML has the same security issues as eval() and should be avoided for [in]security reasons.

(also aesthetically, but that's just me.)



Yes, innerHTML is often misused and a very common source of client-side HTML-injection (DOM-XSS) security holes.

It's usually better to use object-style creation methods, such as createElement, textContent and setting direct DOM properties. Similarly in jQuery, prefer to set variable content using .text() and .prop() rather than .html(), or passing HTML markup to the manipulation methods that allow it.

There are some exceptions though:

  • if you're using a client-side templating language that deals with HTML-escaping for you automatically (eg lodash templates with <%-), it's safe to write the output to innerHTML.

  • if you're appending a lot of siblings to a single element and performance is a priority (the usual example being a <table> with a large number of rows), HTML markup creation can be worth it and you will just have to be careful to HTML-escape all the text manually

  • where the content is actually supposed to be HTML, for example you have data that has been processed from Markdown.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.