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

后端 未结 3 880
佛祖请我去吃肉
佛祖请我去吃肉 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:17

    Check for the arguments object. If it exists, you're in the function. If it doesn't it has been evaled.

    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);
    

    Demo

    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");​
    

提交回复
热议问题