Execute JavaScript code stored as a string

251,012

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.

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.
Share:
251,012

Related videos on Youtube

divinci
Author by

divinci

Updated on April 19, 2022

Comments

  • divinci
    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
    UnkwnTech almost 13 years
    In JS everything can be changed by the user just type "javascript:document.write("Hello World");" into almost any browser's address bar.
  • annakata
    annakata almost 13 years
    super dangerous AND slow - you should bold, italic, underline, and h1 that
  • PatrikAkerstrand
    PatrikAkerstrand almost 13 years
    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 =)
  • cgp
    cgp almost 13 years
    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.
  • Taptronic
    Taptronic almost 13 years
    Good tip on that a simple search about "eval is evil" Thanks!
  • Esben Skov Pedersen
    Esben Skov Pedersen over 12 years
    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.
  • white_gecko
    white_gecko almost 10 years
    If you say eval() is dangerous. Is there any alternative?
  • coobird
    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 running eval on a user-provided string is a serious security issue.
  • Jörn Berkefeld
    Jörn Berkefeld over 8 years
    but in the end - isn't that the same as calling var F=function(){eval(theInstructions);};?
  • G3z
    G3z over 7 years
    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)
  • jkd
    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
    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
    1j01 almost 7 years
    @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.
  • Esben Skov Pedersen
    Esben Skov Pedersen almost 7 years
    @1j01 To be fair my comment is five years old.
  • 1j01
    1j01 almost 7 years
    @EsbenSkovPedersen That's true :)
  • Matthew
    Matthew almost 7 years
    if 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
    Ryu_hayabusa over 6 years
    For 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
    Andrés Morales about 6 years
    @stefan It's beatifull... new Function("alert('Hello World');")()
  • Hossein Hajizadeh
    Hossein Hajizadeh almost 5 years
    @SteelBrain add a sample run by ExecStr("alert(20)",500);
  • Jon
    Jon almost 4 years
    Be 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
    Brendon Shaw over 3 years
    @divinci This is called "Cross Site Scripting". See here: en.wikipedia.org/wiki/Cross-site_scripting.
  • David Edwards
    David Edwards over 3 years
    I 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
    Nelson about 3 years
    The dangerous part is not a user executing code on their machine. It is a user executing someone else's code.
  • Anoop
    Anoop about 3 years
    @DavidEdwards Would be awesome if you still have it and post it.
  • Radvylf Programs
    Radvylf Programs almost 3 years
    Why is Val in InterVal capitalized?
  • Radvylf Programs
    Radvylf Programs almost 3 years
    Rather than saying "eval is evil" and giving no context or solution, this actually tries to solve the issue. +1 for you
  • DADi590
    DADi590 about 2 years
    Would 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
    sziraqui about 2 years
  • jox
    jox about 2 years
    Why 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 the setTimeout call will be invoked before the code passed to setTimeout (even if called with 0 (zero)).
  • atjn
    atjn almost 2 years
    🤷‍♀️ just thought it better explained how setTimeout works
  • Rodgath
    Rodgath almost 2 years
    InterVal is used as an argument, that's why it's capitalized.
  • Bluppie05
    Bluppie05 over 1 year
    wrote it into a one liner return(new Function ("alert('Hello World'); var x = 100")); no idea if this works, i would reccoment just using eval
  • Andrey Ptashinskiy
    Andrey Ptashinskiy 7 months
    One liner should be return(new Function ("alert('Hello World'); var x = 100")());
  • Sebastian Norr
    Sebastian Norr 3 months
    See an extension of this answer here: stackoverflow.com/a/66484305/7880517