0

Is there a way to prevent xss while using innerHTML?

One example:

elem.innerHTML = "Hello <span style='color:red'>There!</span><img src=x onerror=confirm('xss') />");

there can be many more scenarios like this where we just want to show the Pure view part only in the above case only

Hello <span style='color:red'>There!</span><img src=x />

  • I think the following answer may help. https://stackoverflow.com/a/30707806/7432982 – Betelgeuse Jun 30 '21 at 16:01
  • Does this answer your question? [How to prevent script tags in text from executing?](https://stackoverflow.com/q/5440607/90527) – outis Nov 04 '21 at 20:45

1 Answers1

0

You're looking for textContent.

As per MDN:

Element.innerHTML returns HTML, as its name indicates. Sometimes people use innerHTML to retrieve or write text inside an element, but textContent has better performance because its value is not parsed as HTML.

Moreover, using textContent can prevent XSS attacks.

elem.textContent = "Hello <span style='color:red'>There!</span><img src=x onerror=confirm('xss') />";
<pre id="elem"></pre>
Spectric
  • 30,714
  • 6
  • 20
  • 43