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

非 Y 不嫁゛ 提交于 2019-12-02 09:40:00

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!