Google Closure编译器-如何为变量创建外部变量(变量名称不能像在Eval中一样更改) [英] Google Closure Compiler - How to create an Extern for a variable (variable name can't change as it is in an Eval)
问题描述
我在"SIMPLE_OPTIMIZATIONS"模式下使用Google Closure编译器. JavaScript使用"Eval"语句,并将变量"_u"嵌入字符串中.当Google Closure Compiler对代码进行混淆处理时,变量名称更改为"a",并且我收到一个错误,即控制台中未定义"_u".我的理解是,Extern可以解决此问题,但是我不确定如何编写它.有想法吗?
I am using Google Closure Compiler in "SIMPLE_OPTIMIZATIONS" mode. The JavaScript uses an "Eval" statement with the variable "_u" embedded in the string. When Google Closure Compiler obfuscates the code, the variable name is changed to "a" and I get an error that "_u" is not defined in the console. My understanding is that an Extern will solve this problem, but I'm not sure how to write it. Thoughts?
代码段:
var FuncName = (function(){
var ht=escape(_w.location.href)
function _fC(_u){
_aT=_sp+',\\/,\\.,-,_,'+_rp+',%2F,%2E,%2D,%5F';
_aA=_aT.split(',');
for(i=0;i<5;i++){
eval('_u=_u.replace(/'+_aA[i]+'/g,_aA[i+5])')
}
return _u
};
return {
O_LC:function(){
_w.open('https://someurl?referer='+_fC(_ht))
}
};
})();
在Google Closure Compiler修改代码后:
After Google Closure Compiler modifies the code:
var FuncName = function() {
function a(a) {
_aT = _sp + ",\\/,\\.,-,_," + _rp + ",%2F,%2E,%2D,%5F";
_aA = _aT.split(",");
for (i = 0;5 > i;i++) {
eval("_u=_u.replace(/" + _aA[i] + "/g,_aA[i+5])");
}
return a;
}
escape(_w.location.href);
return {O_LC:function() {
_w.open("https://someurl?referer=" + a(_ht));
}};
}();
推荐答案
您只能阻止使用externs重命名全局变量或属性.当地人将始终被重命名.您可以通过多种方法修改代码以解决此问题,包括使用函数构造函数:
You can only prevent renaming of global variables or properties with externs. Locals will always be renamed. You can modify the code in a number of ways to fix this, including using a function constructor:
new Function("_u", "... function body ...")
但是我会重写代码以避免使用eval构造正则表达式.这将起作用:
But I would rewrite the code to avoid using eval to construct the regex. This would work:
_u=_u.replace(new RegExp(_aA[i], "g"), _aA[i+5]);
您可能也对以下内容感兴趣:
You also may be interested in:
有关Closure Compiler限制的一般文档在这里:
General documentation regarding the Closure Compiler limitations are here:
https://developers.google.com/closure/compiler/docs/limitations
这篇关于Google Closure编译器-如何为变量创建外部变量(变量名称不能像在Eval中一样更改)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!