Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using eval() in isolated environment

Tags:

javascript

Is it possible to use eval() to evaluate JavaScript code and be certain that that code will not have access to certain objects?

Example:

(function(window, location){ eval('console.log(window, location)'); })()

The above code doesn't seem to have direct access by reference to the window object because it is undefined in that scope. However, if another object exists globally and it contains a reference to window, it would be accessible.

If I add to window, location any other object or variable that may contain a reference to window, will the evaluated code ever be capable of referencing the window object?

I am trying to create a platform where user apps can be uploaded with js files and access to specific APIs will be given in the form of permissions.

like image 268
Kosmas Papadatos Avatar asked May 26 '15 14:05

Kosmas Papadatos


People also ask

Why eval is not recommended?

Malicious code : invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username. Terribly slow : the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings!

What is a safe alternative to using eval ()?

An alternative to eval is Function() . Just like eval() , Function() takes some expression as a string for execution, except, rather than outputting the result directly, it returns an anonymous function to you that you can call. `Function() is a faster and more secure alternative to eval().

What is the purpose of the eval () method?

The eval() function evaluates JavaScript code represented as a string and returns its completion value.

When should you use eval?

Eval function is mostly used in situations or applications which need to evaluate mathematical expressions. Also if the user wants to evaluate the string into code then can use eval function, because eval function evaluates the string expression and returns the integer as a result.


1 Answers

In JavaScript, any function called globally (i.e. not on an object) will have its this parameter set to the global object (in a browser that is window). So this snippet:

(function(window, lovation) { eval('(function () { console.log(this) })()'); })()

prints out the current window object

like image 72
Will Smith Avatar answered Oct 16 '22 22:10

Will Smith