Hello, I'm Aaron Harun, a New York based
Traveler, Developer and Web Consultant.
You're about to have an "AaHa!" moment.

Executing inline JavaScript when using AJAX

AJAX is full of stumbling blocks. From browser support to user expectations, it can cause more problems than it solves when used at the CMS level. In AJAXed WordPress, I had to find a way to enable javascript processing on arbitrary scripts from other plugins loaded with AJAX. Typically, this is impossible because most inline JS uses the document.write function to output content. Once the page is written with the updated content, document.write is dangerous and can overwrite the entire page.

javascript document

Even more importantly, inline JS is never run when embedded <script> tags are used with the innerHTML command. The following JavaScript function fixes both problems by eval’ing the content of the <script> tags and replacing the default document.write with a new function that replaces the inline JS with the output of the document.write function.

The Code

function executeJS(i){ // Pass an element ID to the function.

	var e = document.getElementById(i); 
	var Reg = '(?:<script.*?>)((\n|.)*?)(?:</script>)'; //Regex for all content between <script> tags.
	var match    = new RegExp(Reg, 'img');
	var scripts  = e.innerHTML.match(match);

	var doc = document.write; // Store the functionality of document.write temporarily.
	//Overwrite document.write with a new function that takes the innerHTML of the passed element
	//then replaces the <script> tag with the output of the passed content.
	document.write = function(p){ e.innerHTML = e.innerHTML.replace(scripts[s],p)};

	if(scripts) { //if matches
		for(var s = 0; s < scripts.length; s++) { //loop through matches
			var js = '';
			var match = new RegExp(Reg, 'im'); //find first match
			js = scripts[s].match(match)[1]; //inner content of the first match
			eval('try{'+js+'}catch(e){}'); //evaluate the inline JS.
		}

	}

	document.write = doc; //Reset document.write back to its original functionality

}

This example function only outputs the first document.write in a script block, so if you require more than one in your embedded JS, it is trivial to store the output content as a variable.

Tagged with: , , ,
Posted in JavaScript

Leave a Reply

Standard Rules Apply: Use <code> tags for code snippets. Keep it relevant. Other than that, be your awesome self.

*(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

The Archive (Sounds ominous, right?)
Categories (Oh! Look at them all)
`