Hi there!
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')?
}
Many thanks!
Hi there!
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')?
}
Many thanks!
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().
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.
eval(s);
But this can be dangerous if you are taking data from users, although I suppose if they crash their own browser thats their problem.
eval(s);
Remember though, that eval is very powerful and quite unsafe. You better be confident that the script you are executing is safe and unmutable by users.
With eval(). See:
http://www.devguru.com/Technologies/ecmascript/quickref/eval.html
Use eval as below. Eval should be used with caution, a simple search about "eval is evil" should throw some pointers.
function ExecuteJavascriptString()
{
var s = "alert('hello')";
eval(s);
}
try this:
var script = "<script type=\"text/javascript\"> content </script>";
//using jquery next
$('body').append(script);//incorporates and executes inmediatelly
//personally i didnt test it. but seems to work.
good look;