Execute JavaScript code stored as a string
How do I execute some JavaScript that is a string?
function ExecuteJavascriptString()
{
var s = "alert('hello')";
// how do I get a browser to alert('hello')?
}
With the eval
function, like:
eval("my script here");
You can execute it using a function. Example:
var theInstructions = "alert('Hello World'); var x = 100";
var F=new Function (theInstructions);
return(F());
The eval
function will evaluate a string that is passed to it.
But the use of eval
can be dangerous, so use with caution.
Edit: annakata has a good point -- Not only is eval
dangerous, it is slow. This is because the code to be evaluated must be parsed on the spot, so that will take some computing resources.
Use eval().
W3 Schools tour of eval. Site has some usable examples of eval. The Mozilla documentation covers this in detail.
You will probably get a lot of warnings about using this safely. do NOT allow users to inject ANYTHING into eval() as it is a huge security issue.
You'll also want to know that eval() has a different scope.
Try this:
var script = "<script type='text/javascript'> content </script>";
//using jquery next
$('body').append(script);//incorporates and executes inmediatelly
Personally, I didn't test it but seems to work.