This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
jQuery uses (new Function(“return ” + data))(); instead of eval(data); to parse JSON, why?
Given a string which represents a valid JSON string, is there a difference between these two parsing methods:
var str, obj;
str = '{"prop":"value"}';
// method 1:
obj = eval( '(' + str + ')' );
// method 2:
obj = ( new Function( 'return (' + str + ');' ) )();
I noticed that jQuery uses the second method to parse JSON strings (in environments that lack a built-in JSON parser). I wonder why they don't use the first method. Why create a function object and invoke it when you can just use eval()?
Please close as exact duplicate
eval is executed within the scope it was declared. Function generates a new function object with its own scope and returns a reference to that function which can be called.
Take this example:
var x = 123;
var y;
function TestEval()
{
var y = 1;
Function("window.alert('Global x: ' + x);")(); //Prints 123
Function("window.alert('Local y: ' + y);")(); //Prints undefined
eval("window.alert('Global x: ' + x);"); //Prints 123
eval("window.alert('Local y: ' + y);"); //Prints 1
}
TestEval();
The first two Function calls will print 123 (the global value of x) and undefined, the global value of y.
The two eval functions will print 123 and 1 (the local value of y). This is because eval has local access to the closure it's being run within. These behaviors (as well as the fact that eval is completely unreliable and inconsistent across many browsers) could be taken advantage of by the jQuery implementation.
Note: Code above tested in Firefox 8, your mileage may vary :)
Using eval is evil because there can be lots of security holes. You are executing code in global scope. Function takes of this differently by executing in its own scope. But one thing Function does better is performance. Looking at this blog shows that Function is almost 2x faster in FF2.
Edit: I am not sure how much more secure it is when you execute document.location = "bad-url", it would still be executed using Function
The global scope thing and also it won't execute anything after a ";" because of the return, that helps a lil bit.
Related
So I'm building a small app where you can evaluate some pieces of JavaScript code, but I'm having a huge "moral" problem:
Initially I wanted to use eval, but I found out about its dangers, so I quickly looked for an alternative.
The closest thing I could find was the function constructor, but for one thing it doesn't evaluate simple pieces of code, such as 2 + 3, since it needs a return statement, whereas eval doesn't, and it's also not that much better security-wise than eval (at least from what I've gathered).
Are there any other ways to evaluate a string as if it were code?
If you want to evaluate JavaScript code, use eval. Is it dangerous? Yes. But that's only because evaluating JavaScript is dangerous. There's no safe way to evaluate JavaScript. If you want to evaluate JavaScript, use eval.
Take every security precaution possible. It's impossible to know what security precautions you should take without knowing more details on what you want to support and how you plan to implement it.
This may be useful:
Is It Possible to Sandbox JavaScript Running In the Browser?
https://github.com/google/caja
You can easily make your own interpreter of JS in JS. I made such thing for www.Photopea.com (File - Scripts, I want to let users execute scripts over PSD documents).
Acorn is an advanced JS parser, which takes a string (JS code) and returns a syntax tree. Then, start at the root of the syntax tree and execute commands one by one.
"Jump" across the tree recursively. Use the JS call stack of the environment as a call stack of the interpreted code. Use JS objects {var1: ..., var2: ...} to store values of variables in each execution space (global, local in a function ...).
You can allow that code to access data from the outer environment through some interface, or make it completely sandboxed. I thought that making my own interpreter would take me a week, but I made it like in 6 hours :)
Please never ever use eval no matter what, there is a much better alternative. Instead of eval, use new function. eval is evil, there's no question about that, but most people skip over the most evil aspect of eval: it gives you access to variables in your local scope. Back in the 90's, back before the concept of JIST compilation, eval's sounded like a good idea (and they were): just insert some additional lines dynamically into the code you're already executing line-by-line. This also meant that evals didn't really slow things down all that much. However, now-a-days with JIST compilation eval statements are very taxing on JIST compilers which internally remove the concept of variable names entirely. For JIST compilers, in order to evaluate an eval statement, it has to figure out where all of its variables are stored, and match them with unknown globals found in the evaled statement. The problem extends even deeper if you get really technical.
But, with new function, the JIST compiler doesn't have to do any expensive variable name lookups: the entire code block is self-contained and in the global scope. For example, take the following terribly inefficient eval snippet. Please note that this is only for the purpose of being an example. In production code, you shouldn't even be using eval or new Function to generate a function from a string whose content is already known.
var a = {
prop: -1
};
var k = eval('(function(b){return a.prop + b;})');
alert( k(3) ); // will alert 2
Now, let's take a look at the much better new Function alternative.
var a = {
prop: -1
};
var k = (new Function('a', 'b', 'return a.prop + b')).bind(undefined, a);
alert( k(3) ); // will alert 2
Notice the difference? There is a major one: the eval is executed inside the local scope while the new Function is executed inside the global one.
Now, onto the next problem: security. There is a lot of talk about how security is difficult, and yes, with eval it is pretty much impossible (e.x. if you wrap the whole code in a sandboxing function, then all you have to do is prematurely end the function and start a new one to execute code freely in the current scope). But, with new Function, you can easily (but not the most efficiently) sandbox anything. Look at the following code.
var whitelist = ['Math', 'Number', 'Object', 'Boolean', 'Array'];
var blacklist = Object.getOwnPropertyNames(window).filter(function(x){
return whitelist.indexOf(x) === -1 && !/^[^a-zA-Z]|\W/.test(x)
});
var listlen = blacklist.length;
var blanklist = (new Array(listlen+1)).fill(undefined);
function sandboxed_function(){
"use-strict";
blacklist.push.apply(blacklist, arguments);
blacklist[blacklist.length-1] =
'"use-strict";' + arguments[arguments.length-1];
var newFunc = Function.apply(
Function,
blacklist
);
blacklist.length = listlen;
return newFunc.bind.apply(newFunc, blanklist);
}
Then, fiddle around with the whitelist, get it just the way you want it, and then you can use sandboxed_function just like new Function. For example:
var whitelist = ['Math', 'Number', 'Object', 'Boolean', 'Array'];
var blacklist = Object.getOwnPropertyNames(window).filter(function(x){
return whitelist.indexOf(x) === -1 && !/^[^a-zA-Z]|\W/.test(x)
});
var listlen = blacklist.length;
var blanklist = (new Array(listlen+1)).fill(undefined);
function sandboxed_function(){
"use-strict";
blacklist.push.apply(blacklist, arguments);
blacklist[blacklist.length-1] =
'"use-strict";' + arguments[arguments.length-1];
var newFunc = Function.apply(
Function,
blacklist
);
blacklist.length = listlen;
return newFunc.bind.apply(newFunc, blanklist);
}
var myfunc = sandboxed_function('return "window = " + window + "\\ndocument = " + document + "\\nBoolean = " + Boolean');
output.textContent = myfunc();
<pre id="output"></pre>
As for writing code to be runned under this strict sandbox, you may be asking, if window is undefined, how do I test for the existence of methods. There are two solutions to this. #1 is just simply to use typeof like so.
output.textContent = 'typeof foobar = ' + typeof foobar;
<div id="output"></div>
As you can see in the above code, using typeof will not throw an error, rather it will only just return undefined. The 2nd primary method to check for a global is to use the try/catch method.
try {
if (foobar)
output.textContent = 'foobar.constructor = ' + foobar.constructor;
else
output.textContent = 'foobar.constructor = undefined';
} catch(e) {
output.textContent = 'foobar = undefined';
}
<div id="output"></div>
So, in conclusion, I hope my code snippets gave you some insight into a much better, nicer, cleaner alternative to eval. And I hope I have aspired you to a greater purpose: snubbing on eval. As for the browser compatibility, while the sandboxed_function will run in IE9, in order for it to actually sandbox anything, IE10+ is required. This is because the "use-strict" statement is very essential to eliminating much of the sneaky sand-box breaking ways like the one below.
var whitelist = ['Math', 'Number', 'Object', 'Boolean', 'Array'];
var blacklist = Object.getOwnPropertyNames(window).filter(function(x){
return whitelist.indexOf(x) === -1 && !/^[^a-zA-Z]|\W/.test(x)
});
var listlen = blacklist.length;
var blanklist = (new Array(listlen+1)).fill(undefined);
function sandboxed_function(){
blacklist.push.apply(blacklist, arguments);
blacklist[blacklist.length-1] =
/*'"use-strict";' +*/ arguments[arguments.length-1];
var newFunc = Function.apply(
Function,
blacklist
);
blacklist.length = listlen;
return newFunc.bind.apply(newFunc, blanklist);
}
var myfunc = sandboxed_function(`return (function(){
var snatched_window = this; // won't work in strict mode where the this
// variable doesn't need to be an object
return snatched_window;
}).call(undefined)`);
output.textContent = "Successful broke out: " + (myfunc() === window);
<pre id="output"></pre>
One last final comment is that if you are going to allow event API's into your sandboxed environment, then you must be careful: the view property can be a window object, making it so you have to erase that too. There are several other things, but I would recommend researching thoroughly and exploring the objects in Chrome's console.
very basic JavaScript programmer here!
I was busy on some code with variables that look like this:
blocktype1;
blocktype2;
blocktype3;
blocktype4;
... //everything between blocktype4 and blocktype70, the three dots are not actual code!
blocktype70;
Now I was using eval() in a function where a value was given to one of the blocktype variables. The blocktype depended on the variable "number".
This is what I had for that part:
eval("blocktype" + number) = 3
What I want is, say "number" is 27, then I want the variable blocktype27 to get a value of 3.
When I check the console it says:
ReferenceError: Invalid left-hand side in assignment
Could anyone possibly help me?
I would prefer just vanilla JavaScript and still the use of eval.
Thank you for your time!
The 'correct' solution would probably be to use an Array which is ideal for sequences and are accessible by index.
var number = 1;
var val = 3;
var blocktype = []; // so clean
blocktype[number] = val;
However, properties can be accessed as with the bracket notation as well. This assumes the variables are in global scope and are thus properties of the global (window) object.
var blocktype1; // .. etc
window["blocktype" + number] = val;
The problem with the eval is that is effectively the same as doing f() = 3 which does not make sense: only variables/properties can be assigned to1.
However eval is a built-in function and the results of a function cannot be assigned to, per the error message. It could be written as
var blocktype1; // .. etc (see dandavis' comment)
eval("blocktype" + number + " = " + val);
// What is actually eval'd is:
// eval("blocktype1 = 3")
which quickly exposes a flaw with eval. If val was the string "Hello world!" with would result in eval("blocktype1 = Hello world!") which is clearly invalid.
1 For the gritty: the left-hand side of an assignment has to be a Reference Specification Type, which is a more wordy way of describining the above behavior. (It is not possible for a JavaScript function to return a RST, although it could technically be done for vendor host objects.)
Feel free not to accept this, since it's specifically not using eval(), but:
You can allocate an array of size 71 like so:
var blocktype = new Array(71);
(your number values apparently start at 1, so we'll have to ignore the first element, blocktype[0], and leave room for blocktype[70], the 71st)
You can now assign elements like this:
blocktype[number] = 3;
and use them like so:
alert( blocktype[number] );
I'm new to Javascript, although I have a .net background. Typically in .NET (as well as many other languages), if a method requires a parameter to be passed, you have to pass it (or else compiler error due to incorrect signature). This also appears to be the case in JavaScript, but not all cases it would appear.
This doesn't appear to be the case in Javascript.
As a working example, please refer to line 61
http://www.humblesoftware.com/flotr2/#!basic-axis
Line 61 is tickFormatter: ticksFn,
I understand that tickFormatter is calling a function called ticksFn but line 29 shows
function ticksFn(n) {
return '(' + n + ')';
}
'ticksFn' requires a value (n) to be passed, yet, we never pass it.
Despite that, javascript still gets it right and I can't find out how, nor can I work/understand what to search for to do more research
You never call it at all. You pass the function itself as an argument (or rather as the value of a property of an object that is an argument).
graph = Flotr.draw(container, [ /* ... */], {
xaxis : {
noTicks : 7, // Display 7 ticks.
tickFormatter : ticksFn, // Displays tick values between brackets.
// …
Your third party library code is responsible for actually calling that function, and it does so with an argument.
In javascript it is not required to pass the parameters for a function as a value of undefined is passed if you don't.
So a function:
function ticksFn(n) {
return '(' + n + ')';
}
Can be invoked:
ticksFn();
Without any problem and the value of the n will be undefined..
Alternatively a function defined with no arguments:
function ticksFn() {
return '(' + arguments[0] + ')';
}
And calling:
ticksFn(10);
arguments[0] will be 10. and accordingly you can read any number of arguments.
That was a quick tutorial about javascript functions.. now about your code.. javascript is a function oriented language and so writing the function name without parentheses actually hands reference on the function rather than calling the function itself..
I'm trying to alert any JavaScript object as a string, in a function. This means if the parameter given to the function is window.document, the actual object, it should alert "window.document" (without quotes) as a literal string.
The following calls...
example(window);
example(window.document);
example(document.getElementById('something'));
...calling this function...
function example(o) {/* A little help here please? */}
...should output the following strings...
window
window.document
document.getElementById('something')
I've attempted to do this with combinations of toString() and eval() among some more miscellaneous shots in the dark without success.
No need insane backwards compatibility, newer ECMAScript / JavaScript features/functions are fine. Feel free to inquire for clarifications though the goal should be pretty straight forward.
This is not possible to do in a self contained script.
If using a preprocessor would be an option, then you could write one which converts example(whatever) into example('whatever'). Other than that I'm afraid you're out of luck.
The first problem is that objects don't have names.
The second problem is that from your examples, you're not really wanting to print the (nonexistent) name of an object, you want to print the expression that evaluated into a reference to an object. That's what you're trying to do in this example:
example(document.getElementById('something'));
For that to print document.getElementById('something'), JavaScript would have had to keep the actual text of that expression somewhere that it would make available to you. But it doesn't do that. It merely evaluates the parsed and compiled expression without reference to the original text of the expression.
If you were willing to quote the argument to example(), then of course it would be trivial:
example( "document.getElementById('something')" );
Obviously in this case you could either print the string directly, or eval() it to get the result of the expression.
OTOH, if you want to try a real hack, here's a trick you could use in some very limited circumstances:
function example( value ) {
var code = arguments.callee.caller.toString();
var match = code.match( /example\s*\(\s*(.*)\s*\)/ );
console.log( match && match[1] );
}
function test() {
var a = (1);
example( document.getElementById('body') );
var b = (2);
}
test();
This will print what you wanted:
document.getElementById('body')
(The assignments to a and b in the test() function are just there to verify that the regular expression isn't picking up too much code.)
But this will fail if there's more than one call to example() in the calling function, or if that call is split across more than one line. Also, arguments.callee.caller has been deprecated for some time but is still supported by most browsers as long as you're not in strict mode. I suppose this hack could be useful for some kind of debugging purposes though.
Don't know why you need this, but you can try walking the object tree recursively and compare its nodes with your argument:
function objectName(x) {
function search(x, context, path) {
if(x === context)
return path;
if(typeof context != "object" || seen.indexOf(context) >= 0)
return;
seen.push(context);
for(var p in context) {
var q = search(x, context[p], path + "." + p);
if(q)
return q;
}
}
var seen = [];
return search(x, window, "window");
}
Example:
console.log(objectName(document.body))
prints for me
window.document.activeElement
What is this line doing:
var tfun = new Function("_", "at" , "with(_) {return (" + text + ");}" );
What is the _, at, and with(_)?
I've read this:
http://www.permadi.com/tutorial/jsFunc/index.html
I understand that it's creating a new function object, but am still quite puzzled at what his is supposed to do.
Forgot to put the source:
http://kite.googlecode.com/svn/trunk/kite.js
http://www.terrainformatica.com/2011/03/the-kite-template-engine-for-javascript/
Here a function is being created that will return the value of the key stored in the variable text on the object passed in to tfun().
When a new Function is created in this manner, the first arguments refer to the parameters of the function and the last argument is the function itself. So here we have two parameters named _ and at and then the function body.
with() is a statement saying to conduct the following lines of code within the context of the object specified. So with(_) is saying to conduct the return statement pulling the key text stored in _.
Here's an example:
var text = "name";
var obj = { "name" : "Bob" };
var tfun = new Function("_", "at" , "with(_) {return (" + text + ");}" );
tfun( obj ); // returns "Bob"
I'm not sure why the at parameter is there as it's not being used.
First comes the function arguments, then code code, so it's basically the same as:
var tfun = function(_, at) {
with(_) { return (eval(text)); };
}
So, whatever is in the text variable will be evaluated and returned from the function.
Note: The use of the eval function should generally be avoided, and as creating code dynamically from a variable does the same thing, it should also generally be avoided. There are a few situations where eval is needed, but most of the time it's not, so you should instead try find out the proper way of doing what you are trying to do.