user2403471
user2403471

Reputation: 9

How can I run a string as if it where javascript code?

How can I run a string as if it where javascript code?

//The user inputs javascript code and clicks run and it runs the javascript code

function getCode () {
    retrun code();
}

funciton runCode() {
    run(getCode());
}

Upvotes: 1

Views: 145

Answers (5)

user1106925
user1106925

Reputation:

While eval() certainly works, another option is to take the code, and pass it to the Function constructor. This creates a new function with your code as the function body.

Doing this has some benefits.

  • it's variable scope will be the global scope, so the code you run won't interfere with any local variables
  • it has much better performance
  • you can force the code into strict mode, and can shadow the window and self identifiers, making it difficult to create global variables

funciton runCode() {
 // create `window` param---v         v--- and `self` param
    var f = new Function("window", "self", "  'use strict';  " + getCode())
                 // force strict mode -----------^
    var self = {}
    f.call(self, self, self); // pass an object to the `window` and `self` param
                              //   and set the same object as the `this` value
}

This certainly doesn't provide full security, but can provide a little more of a "sandbox" for the code to run in.

You can also examine the self object after the call to see if it tried to create any globals.

It may also be useful to wrap the code or the function execution in a try/catch, and then examine any errors that were thrown.

Upvotes: 3

Rob Johnstone
Rob Johnstone

Reputation: 1734

As other posters have indicated, eval is the method that exists for this purpose. However, eval will execute any javascript code regardless of whether it is harmful or not (e.g. javascript from a third party source might have an infinite loop or, worse, malicious behaviour). There is the common refrain

eval == evil

and as such eval is generally regarded as an anti-pattern. However, taking such a simplistic approach is wrong. Instead, it is perfectly acceptable to use eval in cases where the string you wish to evaluate can be trusted. However it turns out there are relatively few cases where this is true. Obviously anything from a third party site is dangerous (even if you trust the owners, they may have been hacked). Even from your own server you may be susceptible to "man in the middle" attacks although this is fairly unlikely for most sites.

The most common reason to need to evaluate javascript strings is rendering third party web pages. In this case it is generally preferable to render the page on the server (e.g. http://phantomjs.org/) and then transmit the result to the browser. That way the browser is protected from running unsafe code.

Another, increasingly common, use case is interactive tutorial websites where the user gets to see the result of the code they have typed in. In this case you are less worried about malicious scripts as the only ones the user will suffer from are those that he/she has typed themselves. But in this case you are still worried about mistakes that will break the functionality of your site (e.g. infinite loops) and so it is still recommended to carry out the evaluation on your server (with appropriate safeguards) so that the inputed javascript cannot break anything.

A possible alternative to eval is Google's caja (https://code.google.com/p/google-caja/) which intends to solve all these problems, however I've never used it myself and can't comment on its usefulness.

Upvotes: 1

ruakh
ruakh

Reputation: 183311

You can use the built-in eval function:

function runCode() {
    eval(getCode());
}

Note that this function is a bit "magical"; the interpreter gives it information from the surrounding lexical context. As a result, it has to be called as eval; you can't set run = eval and then call run. (You could, however, write function run(s) { return eval(s); }.)

Upvotes: 2

Tyler Biscoe
Tyler Biscoe

Reputation: 2422

eval() is the function you're looking for.

But use it wisely or not at all as it's fraught with security risks.

var exec_string = 'alert(\'Hello, World!\')';
eval(exec_string);

Outputs "Hello, World!" in an alert

Upvotes: 2

Barmar
Barmar

Reputation: 781004

The function you want is eval.

function funCode() {
    eval(getCode());
};

Upvotes: 4

Related Questions