Executing <script> injected by innerHTML after AJAX call

JavascriptHtmlAjax

Javascript Problem Overview


There's a div called "Content":

<div id="content"></div>

It should be filled with data from a PHP file, by AJAX, including a <script> tag. However, the script inside this tag is not being executed.

<div id="content"><!-- After AJAX loads the stuff that goes here -->
   <script type="text/javascript">
     //code
   </script>
   <!-- More stuff that DOES work here -->
</div>

Javascript Solutions


Solution 1 - Javascript

I used this code, it is working fine

var arr = MyDiv.getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
    eval(arr[n].innerHTML)//run script inside div

Solution 2 - Javascript

JavaScript inserted as DOM text will not execute. However, you can use the dynamic script pattern to accomplish your goal. The basic idea is to move the script that you want to execute into an external file and create a script tag when you get your Ajax response. You then set the src attribute of your script tag and voila, it loads and executes the external script.

This other StackOverflow post may also be helpful to you: https://stackoverflow.com/questions/1197575/can-scripts-be-inserted-with-innerhtml.

Solution 3 - Javascript

If you load a script block within your div via Ajax like this:

<div id="content">
    <script type="text/javascript">
    function myFunction() {
      //do something
    }
    myFunction();
    </script>
</div>

... it simply updates the DOM of your page, myFunction() does not necessarily get called.

You can use an Ajax callback method such as the one in jQuery's ajax() method to define what to execute when the request finishes.

What you are doing is different from loading a page with JavaScript included in it from the get-go (which does get executed).

An example of how to used the success callback and error callback after fetching some content:

  $.ajax({
    type: 'GET',
    url: 'response.php',
    timeout: 2000,
    success: function(data) {
      $("#content").html(data);
      myFunction();
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      alert("error retrieving content");
    }

Another quick and dirty way is to use eval() to execute any script code that you've inserted as DOM text if you don't want to use jQuery or other library.

Solution 4 - Javascript

Here is the script that will evaluates all script tags in the text.

function evalJSFromHtml(html) {
  var newElement = document.createElement('div');
  newElement.innerHTML = html;
  
  var scripts = newElement.getElementsByTagName("script");
  for (var i = 0; i < scripts.length; ++i) {
    var script = scripts[i];
    eval(script.innerHTML);
  }
}

Just call this function after you receive your HTML from server. Be warned: using eval can be dangerous.

Demo: http://plnkr.co/edit/LA7OPkRfAtgOhwcAnLrl?p=preview

Solution 5 - Javascript

This 'just works' for me using jQuery, provided you don't try to append a subset the XHR-returned HTML to the document. (See this bug report showing the problem with jQuery.)

Here is an example showing it working:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html lang="en"> 
<head> 
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
	<title>test_1.4</title> 
	<script type="text/javascript" charset="utf-8" src="jquery.1.4.2.js"></script> 
	<script type="text/javascript" charset="utf-8"> 
		var snippet = "<div><span id='a'>JS did not run<\/span><script type='text/javascript'>" +
		"$('#a').html('Hooray! JS ran!');" +
		"<\/script><\/div>";
		$(function(){
			$('#replaceable').replaceWith($(snippet));
		});
	</script> 
</head> 
<body> 
	<div id="replaceable">I'm going away.</div> 
</body> 
</html>

Here is the equivalent of the above: http://jsfiddle.net/2CTLH/

Solution 6 - Javascript

Here is a function you can use to parse AJAX responses, especially if you use minifiedjs and want it to execute the returned Javascript or just want to parse the scripts without adding them to the DOM, it handles exception errors as well. I used this code in php4sack library and it is useful outside of the library.

function parseScript(_source) {
	var source = _source;
	var scripts = new Array();
	
	// Strip out tags
	while(source.toLowerCase().indexOf("<script") > -1 || source.toLowerCase().indexOf("</script") > -1) {
		var s = source.toLowerCase().indexOf("<script");
		var s_e = source.indexOf(">", s);
		var e = source.toLowerCase().indexOf("</script", s);
		var e_e = source.indexOf(">", e);
		
		// Add to scripts array
		scripts.push(source.substring(s_e+1, e));
		// Strip from source
		source = source.substring(0, s) + source.substring(e_e+1);
	}
	
	// Loop through every script collected and eval it
  	for(var i=0; i<scripts.length; i++) {
		try {
		  if (scripts[i] != '')
		  { 	    
		    try  {          //IE
		          execScript(scripts[i]);   
      }
      catch(ex)           //Firefox
      {
        window.eval(scripts[i]);
      }   
            
			}  
		}
		catch(e) {
			// do what you want here when a script fails
		 //	window.alert('Script failed to run - '+scripts[i]);
		  if (e instanceof SyntaxError) console.log (e.message+' - '+scripts[i]);
                    }
	}
// Return the cleaned source
	return source;
 }

Solution 7 - Javascript

If you are injecting something that needs the script tag, you may get an uncaught syntax error and say illegal token. To avoid this, be sure to escape the forward slashes in your closing script tag(s). ie;

var output += '<\/script>';

Same goes for any closing tags, such as a form tag.

Solution 8 - Javascript

This worked for me by calling eval on each script content from ajax .done :

$.ajax({}).done(function (data) {      
    $('div#content script').each(function (index, element) { eval(element.innerHTML); 
})  

> Note: I didn't write parameters to $.ajax which you have to adjust > according to your ajax.

Solution 9 - Javascript

I had a similiar post here, https://stackoverflow.com/questions/21594646/addeventlistener-load-on-ajax-load-without-jquery

How I solved it was to insert calls to functions within my stateChange function. The page I had setup was 3 buttons that would load 3 different pages into the contentArea. Because I had to know which button was being pressed to load page 1, 2 or 3, I could easily use if/else statements to determine which page is being loaded and then which function to run. What I was trying to do was register different button listeners that would only work when the specific page was loaded because of element IDs..

so...

if (page1 is being loaded, pageload = 1) run function registerListeners1

then the same for page 2 or 3.

Solution 10 - Javascript

My conclusion is HTML doesn't allows NESTED SCRIPT tags. If you are using javascript for injecting HTML code that include script tags inside is not going to work because the javascript goes in a script tag too. You can test it with the next code and you will be that it's not going to work. The use case is you are calling a service with AJAX or similar, you are getting HTML and you want to inject it in the HTML DOM straight forward. If the injected HTML code has inside SCRIPT tags is not going to work.

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"></head><body></body><script>document.getElementsByTagName("body")[0].innerHTML = "<script>console.log('hi there')</script>\n<div>hello world</div>\n"</script></html>

Solution 11 - Javascript

you can put your script inside an iframe using the srcdoc attribute example:

 <iframe frameborder="0" srcdoc="
       <script type='text/javascript'>
          func();
        </script>
  </iframe>

Solution 12 - Javascript

Another thing to do is to load the page with a script such as:

<div id="content" onmouseover='myFunction();$(this).prop( 'onmouseover', null );'>
<script type="text/javascript">
function myFunction() {
  //do something
}
myFunction();
</script>
</div>

This will load the page, then run the script and remove the event handler when the function has been run. This will not run immediately after an ajax load, but if you are waiting for the user to enter the div element, this will work just fine.

PS. Requires Jquery

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJCOC611View Question on Stackoverflow
Solution 1 - JavascriptFiras NizamView Answer on Stackoverflow
Solution 2 - JavascriptChoculaView Answer on Stackoverflow
Solution 3 - JavascriptChristopher TokarView Answer on Stackoverflow
Solution 4 - JavascriptEvgeniiView Answer on Stackoverflow
Solution 5 - JavascriptPhrogzView Answer on Stackoverflow
Solution 6 - JavascriptAndre Van ZuydamView Answer on Stackoverflow
Solution 7 - JavascriptTommyRayView Answer on Stackoverflow
Solution 8 - JavascriptshivgreView Answer on Stackoverflow
Solution 9 - JavascriptRichard ChaseView Answer on Stackoverflow
Solution 10 - JavascriptAntonio MartinView Answer on Stackoverflow
Solution 11 - JavascriptMoukim hfaiedhView Answer on Stackoverflow
Solution 12 - JavascriptJoshua KleinView Answer on Stackoverflow