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.
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!
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().
The eval() function evaluates JavaScript code represented as a string and returns its completion value.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With