javascriptdominnerhtmlscript-element

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?


Solution

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