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')?
}
share|improve this question

14 Answers 14

up vote 106 down vote accepted

With eval("my script here") function.

share|improve this answer

You can execute it using a function. Example:

var theInstructions = "alert('Hello World'); var x = 100";

var F=new Function (theInstructions);

return(F());
share|improve this answer
1  
but in the end - isn't that the same as calling var F=function(){eval(theInstructions);};? – Jörn Berkefeld Feb 12 '14 at 18:08
3  
yes and no: with eval code would be also executed, while with Function() code isn't executed until F() (use case? check for syntax error but don't want to execute the code) – G3z Jan 3 '15 at 1:02
    
@stefan It's beatifull... new Function("alert('Hello World');")() – Andrés Morales Apr 11 '16 at 21:32
    
you are awesome – Mohsen.Sharify Jan 22 at 11:31

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.

share|improve this answer
23  
super dangerous AND slow - you should bold, italic, underline, and h1 that – annakata Jun 2 '09 at 13:00
4  
I'm doubtful that it's any slower than loading JavaScript anywhere else on the page, that has to be parsed as well. If it's slower, it it's because it's done in a different scope, which might force to creation of resources for that scope. – altCognito Jun 2 '09 at 13:16
2  
If you say eval() is dangerous. Is there any alternative? – white_gecko May 22 '12 at 15:36
1  
@white_gecko It depends on what needs to be accomplished. The "eval can be dangerous" link has a few concrete cases where an alternative to eval is available. One thing that is certain is that running eval on a user-provided string is a serious security issue. – coobird May 22 '12 at 15:43
3  
@coobird I know this is a little late but why is that dangerous? The user can easily run JavaScript code on your website using the console. – jakekimds Ψ Mar 23 '15 at 23:22

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.

share|improve this answer
9  
w3fools.com. The W3C doesn't even have anything to say about eval. If you want to link to something official, target ecma-international.org/ecma-262/5.1/#sec-15.1.2.1 – Bergi Aug 5 '13 at 15:34
6  
I didn't want to "link to anything official, I wanted to link to something readable - Looking at what you linked, it gives no explanation of how it is used, no examples, no way to tinker, and describes the method in isolation. For a beginner, it is a completely inappropriate link. Hey, you wouldn't happen to be @bjorninge, would you? – altCognito Aug 14 '13 at 21:56
1  
The spec describes eval better to me than that W3Schools article. Something readable with good explanation and examples would be developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. And no, I'm not bjorninge – Bergi Aug 15 '13 at 9:36
    
I will agree that it's not documentation, and I will agree that mozilla's page is a better overall picture of it. Slightly tweaked my answer based on feedback – altCognito Aug 15 '13 at 17:14
    
Regarding that ecma-international.org link, I would describe it as readable and appreciable by everyone with more than 15 minutes experience with JS. It's very nice. – i336_ Jan 2 at 11:26

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.

share|improve this answer
1  
You forgot escaping closing > in script: var script = "<script type=\"text/javascript\"> content </script\>"; – rlib Nov 9 '15 at 9:07

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);
}
share|improve this answer
1  
Good tip on that a simple search about "eval is evil" Thanks! – SmartMethod Jun 2 '09 at 13:27
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.

share|improve this answer
1  
exactly. Eval is dangerous on the server side. On the client... not so much. The user could just type in javascript:someevilcode in to the address of the browser and boom. Eval right there. – Esben Skov Pedersen Jan 29 '10 at 9:28
    
@EsbenSkovPedersen That's prevented in chrome at least, and it requires user action, as opposed to a site that evals code from users, which could for instance let users steal other user's accounts without them knowing just by loading the page. – 1j01 May 27 '15 at 1:35
1  
@1j01 To be fair my comment is five years old. – Esben Skov Pedersen May 27 '15 at 7:25
    
@EsbenSkovPedersen That's true :) – 1j01 May 27 '15 at 13:13

Checked this on many complex and obfuscated scripts:

var js = "alert('Hello, World!');" // put your JS code here
var oScript = document.createElement("script");
var oScriptText = document.createTextNode(js);
oScript.appendChild(oScriptText);
document.body.appendChild(oScript);
share|improve this answer

A bit like what @Hossein Hajizadeh alerady said, though in more detail:

There is an alternative to eval().

The function setTimeout() is designed to execute something after an interval of milliseconds, and the code to be executed just so happens to be formatted as a string.

It would work like this:

ExecuteJavascriptString(); //Just for running it

function ExecuteJavascriptString()
{
    var s = "alert('hello')";
    setTimeout(s, 1);
}

1 means it will wait 1 millisecond before executing the string.

It might not be the most correct way to do it, but it works.

share|improve this answer
    
Anyone care to explain to me why i'm downvoted? – Anton Juul-Naber Jul 29 '16 at 8:59

eval should do it.

eval(s);
share|improve this answer

Not sure if this is cheating or not:

window.say = function(a) { alert(a); };

var a = "say('hello')";

var p = /^([^(]*)\('([^']*)'\).*$/;                 // ["say('hello')","say","hello"]

var fn = window[p.exec(a)[1]];                      // get function reference by name

if( typeof(fn) === "function") 
    fn.apply(null, [p.exec(a)[2]]);                 // call it with params
share|improve this answer
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.

share|improve this answer
1  
In JS everything can be changed by the user just type "javascript:document.write("Hello World");" into almost any browser's address bar. – UnkwnTech Jun 2 '09 at 12:58
1  
Yes, but you can make it harder for him by not using global variables, hiding your functions in closures etc. Also, by avoiding eval like the plague =) – PatrikAkerstrand Jun 2 '09 at 13:05

New Function and apply() together works also

var a=new Function('alert(1);')
a.apply(null)
share|improve this answer

If you want to execute a specific command (that is string) after a specific time

function ExecStr(cmd, InterVal) {
    try {
        setTimeout(function () {
            var F = new Function(cmd);
            return (F());
        }, InterVal);
    } catch (e) { }
}
window.ExecStr = ExecStr;
share|improve this answer
1  
please do explain – Steel Brain Oct 8 '14 at 9:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.