Restricting eval() to a narrow scope

前端 未结 8 2157
误落风尘
误落风尘 2020-11-27 04:51

I have a javascript file that reads another file which may contain javascript fragments that need to be eval()-ed. The script fragments are supposed to conform to a strict s

8条回答
  •  爱一瞬间的悲伤
    2020-11-27 05:09

    Short answer: No. If it's in the global scope, it's available to anything.

    Long answer: if you're eval()ing untrusted code that really wants to read or mess with your execution environment, you're screwed. But if you own and trust all code being executed, including that being eval()ed, you can fake it by overriding the execution context:

    function maskedEval(scr)
    {
        // set up an object to serve as the context for the code
        // being evaluated. 
        var mask = {};
        // mask global properties 
        for (p in this)
            mask[p] = undefined;
    
        // execute script in private context
        (new Function( "with(this) { " + scr + "}")).call(mask);
    }
    

    Again, I must stress:

    This will only serve to shield trusted code from the context in which it is executed. If you don't trust the code, DO NOT eval() it (or pass it to new Function(), or use it in any other way that behaves like eval()).

提交回复
热议问题