我已经为我的应用程序运行了安全扫描仪,它一般说:
“eval() 是一个危险的函数,它以调用者的所有权限执行代码 双方。如果对可能受影响的字符串运行 eval() 攻击者,那么您可以在设备上运行恶意代码 有权访问您的网页/扩展程序的用户。”
这是我之前的代码
Date.createNewFormat = function(format) {
console.log('format 22', format)
var funcName = "format" + Date.formatFunctions.count++;
Date.formatFunctions[format] = funcName;
var code = "Date.prototype." + funcName + " = function() {return ";
var special = false;
var ch = "";
for (var i = 0; i < format.length; ++i) {
ch = format.charAt(i);
if (!special && ch == "\\") {
special = true;
} else {
if (special) {
special = false;
code += "'" + String.escape(ch) + "' + ";
} else {
code += Date.getFormatCode(ch);
}
}
}
eval(code.substring(0, code.length - 3) + ";}");
}
因此更改了新函数的 eval,我不知道这是否可以修复扫描仪测试中的错误
var runFunction = new Function(code.substring(0, code.length - 3) + ";}");
runFunction();
您可以在以下情况下计算格式字符串,而不是将格式函数构建为您
eval()
的字符串:
Date.createNewFormat = function(format) {
console.log('format 22', format)
let funcName = "format" + Date.formatFunctions.count++;
Date.formatFunctions[format] = funcName;
let funcArray = [];
for (var i = 0; i < format.length; ++i) {
let ch = format[i];
if (ch == "\\" && i < format.length-1) {
// use next character literally and skip over it
funcArray.push(() => format[i++]);
} else {
funcArray.push(Date.getFormatCode(ch));
}
}
Date.prototype[funcName] = function() {
return funcArray.map(f => f.call(this));
}
}
您需要更改 Date.getFormatCode()
,这样它就不会以字符串形式返回代码,而是返回函数。这些函数应引用
this
来访问正在格式化的
Date
对象(正如我假设您的字符串版本所做的那样)并返回格式化值。