-2

From what I understand, setting innerHTML on an element is bad, because if the new contents come from users, a malicious user can use it to inject <script> tags and other harmful content.

As demonstrated by this question, there are now about eight different alternative tags (with some non-standard).

In my case, I want to be able to insert actual html tags like <b> and <i>, and even <a>.

But I never need <script> to be inserted.

Is there a standardized best-practice alternative to innerHTML using vanilla Javascript?

Jamin Grey
  • 10,151
  • 6
  • 39
  • 52
  • 1
    You could always give dompurify a try. https://github.com/cure53/DOMPurify – boostedd Dec 05 '21 at 01:02
  • 1
    Where is your formatted text coming from? Users? How much HTML do they have available to them? – Ry- Dec 05 '21 at 01:18
  • 1
    Maybe use bbcode instead? https://www.bbcode.org/ – user2182349 Dec 05 '21 at 01:54
  • @Ry- Well, it's loaded from the server in JSON files, but shouldn't ever be editable by users. I was just unsure of what the standard practice for this is. I'll sanitize it with DOMPurify (thanks, @boostedd!) – Jamin Grey Dec 06 '21 at 17:52
  • 1
    If the author of the HTML is the same as the author of the JavaScript, don’t sanitize it on the client unnecessarily. That’s unneeded bloat and/or security theatre. If the HTML is provided by translators or something, sanitize as a step between those source files and the JSON files that the client reads. – Ry- Dec 06 '21 at 22:25

1 Answers1

0

There are a million things you can mess up that will allow XSS if you do this yourself. Your best option is a library to sanitize the html for you.

See some options here Sanitize/Rewrite HTML on the Client Side

After you've sanitized it matters less which property you set.

nlta
  • 1,716
  • 1
  • 7
  • 17