Does there exist a string s
such that
(new Function(s))();
and
eval(s);
behave differently? I'm trying to "detect" how a string is being evaluated.
Check for the arguments
object. If it exists, you're in the function. If it doesn't it has been eval
ed.
Note that you'll have to put the check for arguments
in a try...catch
block like this:
var s = 'try {document.writeln(arguments ? "Function" : "Eval") } catch(e) { document.writeln("Eval!") }';
(new Function(s))();
eval(s);
Solution to nnnnnn
's concern. For this, I've edited the eval function itself:
var _eval = eval;
eval = function (){
// Your custom code here, for when it's eval
_eval.apply(this, arguments);
};
function test(x){
eval("try{ alert(arguments[0]) } catch(e){ alert('Eval detected!'); }");
}
test("In eval, but it wasn't detected");