字符串函数安全解析成执行函数
可以通过创建沙箱环境(注入组件方法和工具函数)使用组件内部函数
function safeParseFunction(fnStr: string, context = {}) {
if (typeof fnStr !== 'string') return fnStr;
const processedStr = fnStr
.trim()
.replace(/\\n/g, '\n')
.replace(/\\t/g, ' ')
.replace(/\\"/g, '"')
.replace(/\r/g, '')
.replace(/\s+/g, ' ');
try {
const sandbox = {
...context,
console,
setTimeout,
clearTimeout,
setInterval,
clearInterval
};
const createExecutor = () => {
const sandboxKeys = Object.keys(sandbox);
const params = sandboxKeys.join(', ');
let fnBody = processedStr;
if (fnBody.includes('=>')) {
if (!fnBody.startsWith('(')) {
fnBody = `(${fnBody})`;
}
} else if (!fnBody.startsWith('function')) {
fnBody = `function() { ${fnBody} }`;
}
return new Function(params, `return (${fnBody}).apply(this, arguments)`);
};
const executor = createExecutor();
return (...args) =>
executor.apply(sandbox, Object.values(sandbox).concat(args));
} catch (error: any) {
console.error('[函数解析失败]', {
input: fnStr,
error: error.message
});
return () => {};
}
}
const testFunction = safeParseFunction(
"()=>{\n console.log(11);\n setTimeout(()=>{console.log(12)},100);\n}"
);
testFunction();