1

I am appending a script tag, along with a bunch of other html, to my current document, retrieved from an ajax call. For some reason the script is not running

//Response handling function
function(responseText){
    document.getElementById('reportContainer').insertAdjacentHTML('afterbegin',responseText);
}

An example of responseText's contents:

<h2>You are <em class="won">victorious</em>!</h2>
<h3>Earnings</h3>
... 
<script>
    alert('dgd');
</script>

All the html is getting applied to the document, including the script, but it is not running, I don't get this alert popping. What may be causing this?

6
  • Why don't you use innerHTML ? Commented Jun 14, 2014 at 16:52
  • @RashminJaviya i tried it, no luck. Commented Jun 14, 2014 at 16:53
  • 1
    Why don't you use jQuery :) Commented Jun 14, 2014 at 16:55
  • @RashminJaviya because I don't like it :D Commented Jun 14, 2014 at 16:56
  • 2
    Scripts injected via markup strings are intentionally ignored to avoid XSS. developer.mozilla.org/en-US/docs/Web/API/…. The contents of the <script> will have to be evaled to be executed. stackoverflow.com/questions/1197575/… Commented Jun 14, 2014 at 17:03

3 Answers 3

1

Check the following snippet and call the function as

var newEle = document.querySelector("#reportContainer");
exec_body_scripts(newEle);

Function

exec_body_scripts = function(body_el) {
  // Finds and executes scripts in a newly added element's body.
  // Needed since innerHTML does not run scripts.
  //
  // Argument body_el is an element in the dom.

  function nodeName(elem, name) {
    return elem.nodeName && elem.nodeName.toUpperCase() ===
              name.toUpperCase();
  };

  function evalScript(elem) {
    var data = (elem.text || elem.textContent || elem.innerHTML || "" ),
        head = document.getElementsByTagName("head")[0] ||
                  document.documentElement,
        script = document.createElement("script");

    script.type = "text/javascript";
    try {
      // doesn't work on ie...
      script.appendChild(document.createTextNode(data));      
    } catch(e) {
      // IE has funky script nodes
      script.text = data;
    }

    head.insertBefore(script, head.firstChild);
    head.removeChild(script);
  };

  // main section of function
  var scripts = [],
      script,
      children_nodes = body_el.childNodes,
      child,
      i;

  for (i = 0; children_nodes[i]; i++) {
    child = children_nodes[i];
    if (nodeName(child, "script" ) &&
      (!child.type || child.type.toLowerCase() === "text/javascript")) {
          scripts.push(child);
      }
  }

  for (i = 0; scripts[i]; i++) {
    script = scripts[i];
    if (script.parentNode) {script.parentNode.removeChild(script);}
    evalScript(scripts[i]);
  }
};
Sign up to request clarification or add additional context in comments.

Comments

0

It won't execute when you push it into the DOM in this way. Can you use jQuery? It will execute it:

$('#reportContainer').append('<script type="text/javascript">alert(123);</script>');

3 Comments

OP has not mention jquery tag in answer
I thought insertAdjacentHTML is doing exactly that - converting string to DOM objects? I don't use jQuery
Then you won't be able to do it as the browsers don't execute the script. Under the hood, jQuery does. It most likely parses the string you're attempting to insert and eval()s it. Can you use jQuery?
0

What you get from ajax call is plain text or XML that can be inserted into DOM as HTML fragment, but all javascript code is explicitly forbidden for security reasons. There are plenty of choices to workaround this situation - from extracting part in the responseText and using eval method (not recommended, bad practice) to using of jQuery.load method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.