Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Thursday, June 19, 2008

JavaScript parsing and evaluation

By default script tags are not parsed and evaluated by browsers when you try to inject them as regular text ( for example using innerHTML). Following code borrowed from mootools library will do it for you.

var myText = "html here <script>alert('javascript eval worked');</script>";
var scripts = [];
var regexp = /<script[^>]*>([\s\S]*?)<\/script>/gi;
while ((script = regexp.exec(myText))) scripts.push(script[1]);
scripts = scripts.join('\n');
if (scripts) (window.execScript) ? window.execScript(scripts) : window.setTimeout(scripts, 0);