Home > Software engineering >  Scritp tag contained in a dynamically appended DOM element does not execute
Scritp tag contained in a dynamically appended DOM element does not execute

Time:02-16

If I try to do something like this:

let div = document.createElement('DIV');
div.innerHTML="<script>console.log('test');</script>";
document.body.appendChild(div);

no message is shown. Also there are no CSP warnings / errors.

Is this a security feature?

Please do not post an answer that it is possible to inject a script tag directly, I'm aware of this.

CodePudding user response:

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

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

CodePudding user response:

As Maciej said, you cannot do that with innerHTML.

But you could write a small script that would execute (replace with a normal script) the inserted script afterwards.

const div = document.createElement('DIV');
div.innerHTML = "<script>console.log('test');<\/script>YO";
document.body.appendChild(div);

executeScriptsInNode(div);

function executeScriptsInNode(node) {
  const scripts = node.querySelectorAll('script');
  scripts.forEach(script => {
    const scriptNode = document.createElement('SCRIPT');
    scriptNode.text = script.innerHTML;
    script.parentNode.replaceChild(scriptNode, script);
  })
}

  • Related