我有一个 javascript 文件读取另一个文件,该文件可能包含需要 eval() 的 javascript 片段。脚本片段应该符合 javascript 的严格子集,限制它们可以做什么以及可以更改哪些变量,但我想知道是否有某种方法可以通过防止 eval 在全局范围内查看变量来强制执行此操作.类似于以下内容:
function safeEval( fragment )
{
var localVariable = g_Variable;
{
// do magic scoping here so that the eval fragment can see localVariable
// but not g_Variable or anything else outside function scope
eval( fragment );
}
}
实际代码不需要看起来像这样——我对闭包等所有奇怪的技巧持开放态度。但我确实想知道这是否可能。
最佳答案
简短回答:不。如果它在全局范围内,它对任何事物都可用。
长答案:如果您正在eval()
真正想要读取或扰乱您的执行环境的不受信任的代码,您搞砸了。但是,如果您拥有并信任所有正在执行的代码,包括正在执行 eval()
的代码,您可以通过覆盖执行上下文来伪造它:
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);
}
再次,我必须强调:
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 newFunction()
, or use it in any other way that behaves likeeval()
).
关于javascript - 将 eval() 限制在一个狭窄的范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/543533/