Executing [removed] elements inserted with [removed]

后端 未结 20 2562
囚心锁ツ
囚心锁ツ 2020-11-22 00:12

I\'ve got a script that inserts some content into an element using innerHTML.

The content could for example be:



        
20条回答
  •  攒了一身酷
    2020-11-22 00:49

    A solution without using "eval":

    var setInnerHtml = function(elm, html) {
      elm.innerHTML = html;
      var scripts = elm.getElementsByTagName("script");
      // If we don't clone the results then "scripts"
      // will actually update live as we insert the new
      // tags, and we'll get caught in an endless loop
      var scriptsClone = [];
      for (var i = 0; i < scripts.length; i++) {
        scriptsClone.push(scripts[i]);
      }
      for (var i = 0; i < scriptsClone.length; i++) {
        var currentScript = scriptsClone[i];
        var s = document.createElement("script");
        // Copy all the attributes from the original script
        for (var j = 0; j < currentScript.attributes.length; j++) {
          var a = currentScript.attributes[j];
          s.setAttribute(a.name, a.value);
        }
        s.appendChild(document.createTextNode(currentScript.innerHTML));
        currentScript.parentNode.replaceChild(s, currentScript);
      }
    }
    

    This essentially clones the script tag and then replaces the blocked script tag with the newly generated one, thus allowing execution.

提交回复
热议问题