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

1

0

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.)

Addicted answered 24/3, 2015 at 6:32 Comment(0)
M
1

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.

Mohl answered 24/3, 2015 at 10:12 Comment(1)
the first and third cases are the same: you're relying on (someone else's) a code scrubber for your security. in the case of the markdown, it seems more of a bug than a feature that the output is html. the second case seems to be a browser anomaly: that currently html text renders faster than DOM manipulation, something that should get better as pages are becoming more dynamic.Addicted

© 2022 - 2024 — McMap. All rights reserved.