Execute JavaScript code stored as a string
Solution 1
With the eval
function, like:
eval("my script here");
Solution 2
You can execute it using a function. Example:
var theInstructions = "alert('Hello World'); var x = 100";
var F=new Function (theInstructions);
return(F());
Solution 3
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.
Solution 4
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.
Solution 5
For users that are using node and that are concerned with the context implications of eval()
nodejs offers vm
. It creates a V8 virtual machine that can sandbox the execution of your code in a separate context.
Taking things a step further is vm2
which hardens vm
allowing the vm to run untrusted code.
https://nodejs.org/api/vm.html - Official nodejs/vm
https://github.com/patriksimek/vm2 - Extended vm2
const vm = require('vm');
const x = 1;
const sandbox = { x: 2 };
vm.createContext(sandbox); // Contextify the sandbox.
const code = 'x += 40; var y = 17;';
// `x` and `y` are global variables in the sandboxed environment.
// Initially, x has the value 2 because that is the value of sandbox.x.
vm.runInContext(code, sandbox);
console.log(sandbox.x); // 42
console.log(sandbox.y); // 17
console.log(x); // 1; y is not defined.
Related videos on Youtube

divinci
Updated on April 19, 2022Comments
-
divinci 30 days
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')? }
-
UnkwnTech almost 13 yearsIn JS everything can be changed by the user just type "javascript:document.write("Hello World");" into almost any browser's address bar.
-
annakata almost 13 yearssuper dangerous AND slow - you should bold, italic, underline, and h1 that
-
PatrikAkerstrand almost 13 yearsYes, 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 =)
-
cgp almost 13 yearsI'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.
-
Taptronic almost 13 yearsGood tip on that a simple search about "eval is evil" Thanks!
-
Esben Skov Pedersen over 12 yearsexactly. 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.
-
white_gecko almost 10 yearsIf you say
eval()
is dangerous. Is there any alternative? -
coobird almost 10 years@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 runningeval
on a user-provided string is a serious security issue. -
Jörn Berkefeld over 8 yearsbut in the end - isn't that the same as calling
var F=function(){eval(theInstructions);};
? -
G3z over 7 yearsyes 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)
-
jkd about 7 years@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.
-
Moishe Lipsker almost 7 years@jakeimds it can be dangerous if that javascript string is passed to a different user's browser and evaluated there
-
1j01 almost 7 years@EsbenSkovPedersen That's prevented in chrome at least, and it requires user action, as opposed to a site that
eval
s code from users, which could for instance let users steal other user's accounts without them knowing just by loading the page. -
Esben Skov Pedersen almost 7 years@1j01 To be fair my comment is five years old.
-
1j01 almost 7 years@EsbenSkovPedersen That's true :)
-
Matthew almost 7 yearsif your security depends at all on client-side javascript, you've screwed up big time and it has nothing to do with eval.
-
Ryu_hayabusa over 6 yearsFor the people who are wondering why this is dangerous. If we are allowing eval() on user content say a comment field on your blog site. somebody can write javascript there to steal cookies of other users who are visiting the same page, or redirect users to a malacious site. For more info read about cross site scripting.
-
Andrés Morales about 6 years@stefan It's beatifull...
new Function("alert('Hello World');")()
-
Hossein Hajizadeh almost 5 years@SteelBrain add a sample run by ExecStr("alert(20)",500);
-
Jon almost 4 yearsBe carefull ! This gonna execute the code therefore be careful of where/how you got this string. Mind that anyone may try to insert malicious code inside your string.
-
Brendon Shaw over 3 years@divinci This is called "Cross Site Scripting". See here: en.wikipedia.org/wiki/Cross-site_scripting.
-
David Edwards over 3 yearsI tried this inside a try/catch block, and it works perfectly. I can now take any JavaScript code typed into a text block, pass it to my function, and execute it. The catch block can then insert error messages from the JavaScript engine into a DOM element and display any errors in the code. If someone wants the function I wrote, then once I've tidied it up, I can post it here.
-
Nelson about 3 yearsThe dangerous part is not a user executing code on their machine. It is a user executing someone else's code.
-
Anoop about 3 years@DavidEdwards Would be awesome if you still have it and post it.
-
Radvylf Programs almost 3 yearsWhy is
Val
inInterVal
capitalized? -
Radvylf Programs almost 3 yearsRather than saying "eval is evil" and giving no context or solution, this actually tries to solve the issue. +1 for you
-
DADi590 about 2 yearsWould this be faster than using eval() - not considering the part where eval is dangerous, forgetting that now. Is it faster? Or it's all the same because the code is in a string and it gets slow too? (Is the problem of slowness of eval() being in the code being in a string?)
-
sziraqui about 2 yearsThis is better than
eval()
. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
jox about 2 yearsWhy waste one millisecond when you can pass 0 (zero) to
setTimeout
? Note that in any case it will make the execution asynchronous. It means that all code that follows thesetTimeout
call will be invoked before the code passed tosetTimeout
(even if called with 0 (zero)). -
atjn almost 2 years🤷♀️ just thought it better explained how setTimeout works
-
Rodgath almost 2 yearsInterVal is used as an argument, that's why it's capitalized.
-
Bluppie05 over 1 yearwrote it into a one liner
return(new Function ("alert('Hello World'); var x = 100"));
no idea if this works, i would reccoment just usingeval
-
Andrey Ptashinskiy 7 monthsOne liner should be
return(new Function ("alert('Hello World'); var x = 100")());
-
Sebastian Norr 3 monthsSee an extension of this answer here: stackoverflow.com/a/66484305/7880517