javascript - Executing <script> elements inserted with .innerHTML - Stack Overflow

PHOTO EMBED

Tue Nov 30 2021 06:28:53 GMT+0000 (UTC)

Saved by @kp7860 #javascript

var setInnerHTML = function(elm, html) {
  elm.innerHTML = html;
  Array.from(elm.querySelectorAll("script")).forEach( oldScript => {
    const newScript = document.createElement("script");
    Array.from(oldScript.attributes)
      .forEach( attr => newScript.setAttribute(attr.name, attr.value) );
    newScript.appendChild(document.createTextNode(oldScript.innerHTML));
    oldScript.parentNode.replaceChild(newScript, oldScript);
  });
}
content_copyCOPY

https://stackoverflow.com/questions/2592092/executing-script-elements-inserted-with-innerhtml