Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do `<script>` elements inserted through `.innerHTML` not get executed?

Is it specified that element.innerHTML = '<script>alert()</script>'; does execute the inserted script, or does behaviour vary between browsers? Can I rely on innerHTML not executing scripts?

like image 518
ituy Avatar asked Nov 29 '25 19:11

ituy


1 Answers

In HTML5 the behavior is specified to not execute inserted <script> elements, however as this page from Mozilla notes, there are still ways to get around this to execute JavaScript, so you can't rely on this for security.

HTML5 Spec: https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0

script elements inserted using innerHTML do not execute when they are inserted.

https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Security_considerations

there is still a security risk whenever you use innerHTML to set strings over which you have no control. For example:

const name = "<img src='x' onerror='alert(1)'>";
el.innerHTML = name; // shows the alert

For that reason, it is recommended that instead of innerHTML you use:

  • Element.SetHTML() to sanitize the text before it is inserted into the DOM.
  • Node.textContent when inserting plain text, as this inserts it as raw text rather than parsing it as HTML.
like image 166
Billy Hudson Avatar answered Dec 01 '25 09:12

Billy Hudson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!