How can I detect I'm inside an eval() call?

后端 未结 3 890
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-01 06:40

Does there exist a string s such that

(new Function(s))();

and

eval(s);

behave differently? I\'

3条回答
  •  心在旅途
    2021-02-01 07:25

    The current answer does not work in strict mode since you can't redefine eval. Moreover, redefining eval is problematic for many other reasons.

    The way to differenciate them is based on the fact that well... one of them creates a function and what doesn't. What can functions do? They can return stuff :)

    We can simply exploit that and do something with return:

    // is in function
    try {
         return true;
    } catch(e) { // in JS you can catch syntax errors
         false; //eval returns the return of the expression.
    }
    

    So in example:

    var s = "try{ return true; }catch(e){ false; }";
    eval(s); // false
    Function(s)(); // true
    (new Function(s))(); // true, same as line above
    (function(){ return eval(s); })(); // the nested 'problematic' case - false
    

提交回复
热议问题