I have a WordPress plugin that loads pages with AJAX and to ensure compatibility with other plugins and "widgets."
As of right now I use the following code to evaluate all inline JS that is inside the content blocks to be updated:
function do_JS(e){
var Reg = '(?:<script.*?>)((\n|.)*?)(?:</script>)';
var match = new RegExp(Reg, 'img');
var scripts = e.innerHTML.match(match);
var doc = document.write;
document.write = function(p){ e.innerHTML = e.innerHTML.replace(scripts[s],p)};
if(scripts) {
for(var s = 0; s < scripts.length; s++) {
var js = '';
var match = new RegExp(Reg, 'im');
js = scripts[s].match(match)[1];
js = js.replace('<!--','');
js = js.replace('-->','');
eval('try{'+js+'}catch(e){}');
}
}
document.write = doc;
}
I'd like to be able to sandbox the JS a bit better so that the risk of conflicts are minimized. One idea I had was to dynamically create an <iframe>
and run the JS inside of it, but I was hoping there was a bit better method to both ensure compatibility and increase security.