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')?
}
How do I execute some JavaScript that is a string?
|
||||
|
With |
||||
|
You can execute it using a function. Example:
|
|||||||||||||||||
|
The But the use of Edit: annakata has a good point -- Not only is |
|||||||||||||||||||||
|
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:
Personally I didnt test it, but seems to work. |
|||||
|
Use eval as below. Eval should be used with caution, a simple search about "eval is evil" should throw some pointers.
|
|||||
|
But this can be dangerous if you are taking data from users, although I suppose if they crash their own browser thats their problem. |
|||||||||||||||||
|
Checked this on many complex and obfuscated scripts:
|
|||
|
A bit like what @Hossein Hajizadeh alerady said, though in more detail: There is an alternative to The function It would work like this:
It might not be the most correct way to do it, but it works. |
|||||
|
eval should do it.
|
|||
|
Not sure if this is cheating or not:
|
|||
|
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. |
|||||||||
|
New Function and apply() together works also
|
|||
|
If you want to execute a specific command (that is string) after a specific time
|
|||||
|