我正在尝试获取脚本中已使用但未声明的变量列表。我正在创建一个更好的代码混淆器,但有一件事是,由于范围的设置,混淆的脚本无法访问外部变量(这是故意的)。所以我试图通过“转移”脚本外部使用的变量来修复它。假设我有一个函数:
var somevar = " world"; // this represents non obfuscated "outside" code
(function() { // This represents the obfuscated code
var a = "hello";
console.log(a + somevar);
})();
我希望能够做到这一点:
var somevar = " world";
(function(console,somevar) {
var a = "hello";
console.log(a + somevar);
})(console,somevar)
但为了做到这一点,我必须获取已使用但未在函数内声明的变量列表。 (console
和somevar
是未声明的变量,它们在函数中未声明,但已被使用)
顺便说一句:这基本上是一个字符串操作问题
编辑:一些澄清
我正在尝试从 STRING 中获取列表。因此使用 window
将不起作用
编辑:更多说明
由于我正在制作混淆脚本,因此它不会运行要混淆的脚本,我只是将未评估的脚本作为字符串。
编辑:更多说明
如果我将其输入到此问题的答案中:
"var a = 'foo';console.log(a + b)"
应该输出
["b","console"]
最佳答案
您可以将 with
语句与代理一起使用:
var somevar = " world"; // this represents non obfuscated "outside" code
var externalVars = [];
with(new Proxy(Object.create(null), {
has: function(_, identifier) {
externalVars.push(identifier);
}
})) (function() { // This represents the obfuscated code
var a = "hello";
console.log(a + somevar);
})();
console.log("External vars:", externalVars);
如果您拥有的是带有代码的字符串,那么您可以使用eval
。
var somevar = " world"; // this represents non obfuscated "outside" code
var externalVars = [];
with(new Proxy(Object.create(null), {
has: function(_, identifier) {
externalVars.push(identifier);
return !(identifier in window);
}
})) (function() { // This represents the obfuscated code
eval("var a = 'foo';console.log(a + b)");
})();
console.log("External vars:", externalVars);
如果您不想运行代码而只想获取标识符,则可以添加额外的代理陷阱,以便仅让代码处理代理膜,从而防止副作用。请注意,这可能很难正确完成,并且如果存在条件或循环,代码的行为可能会有所不同。
var somevar = " world"; // this represents non obfuscated "outside" code
var externalVars = [];
var proxy = new Proxy(function(){}, {
apply: function() {
return proxy;
},
has: function(_, identifier) {
externalVars.push(identifier);
return true;
},
get: function(_, identifier) {
if (identifier === Symbol.toPrimitive) return () => null;
if (identifier === Symbol.unscopables) return undefined;
return proxy;
}
// Add necessary traps
});
with(proxy) (function() { // This represents the obfuscated code
var a = "hello";
console.log(a + somevar);
})();
console.log("External vars:", externalVars);
关于javascript - 获取未在函数内声明的所使用变量的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41652574/