Search code examples
javascripthtmldominnerhtmlinsertadjacenthtml

Are there any security risks with using insertAdjacentHTML when wanting append HTML to a document?


I have recently found out that using setInnerHtml is not good practice as there are plenty performance and security issues associated with it. So I am wondering whether replacing setInnerHtml with "insertAdjacentHTML" is fine?

Also, how should I go about completely refilling a table? As in removing the children of the parent element, the table body, and repopulating it with insertAdjacentHTML.

What I am currently doing

document.getElementById('myid').innerHTML = "";
const elm = document.getElementById("myid");
elm.insertAdjacentHTML('beforeend', '<div></div>');

Does this practice defeat the purpose of using insertAdjacentHTML since I am still using innerHTML. When I set it empty with innerHTML, I am not doing any complex DOM manipulation, am I?


Solution

  • If the HTML to be inserted is not trustworthy, insertAdjacentHTML could allow for arbitrary code execution.

    const evilInput = `<img src onerror="alert('evil')">`;
    document.body.insertAdjacentHTML('beforeend', evilInput);

    In terms of security, insertAdjacentHTML is not really better than innerHTML - what insertAdjacentHTML is useful for is when

    • other elements in the container have a listener attached to them, and you don't want to corrupt the listeners by assigning to innerHTML. Or
    • when you have a reference to an element and want to insert something next to it instead of taking a longer method (such as selecting the parent and then using insertBefore)

    Also, how should I go about completely refilling a table?

    Setting the text content or innerHTML to the empty string and then choosing any of the safe approaches to insert elements anew is fine. (What qualifies as a safe approach depends on what exactly you're inserting. If it's from your trustworthy backend, for example, innerHTML and insertAdjacentHTML are both fine - use whatever makes the logic easiest)