代码没有在javascript的eval中执行

Code not executing in eval in javascript

本文关键字:eval 执行 javascript 代码      更新时间:2023-09-26

我知道'eval '是邪恶的',但在salesforce的标准功能是使用eval在点击按钮时执行脚本,这个eval脚本在页面上是可用的。现在,我以某种方式获得脚本并从中提取eval部分。但是由于某些原因,我不能执行eval字符串。

    var accountId;
    var functionName = j$("[name=click_me]").attr('onclick');
    __fromScript=true;
    var temp = j$("[name=click_me]:first");
    //get the function name from the onclick attribute.
    var evalString = eval(functionName.substring(4,42));
    console.log('the eval string is '+ evalString);
    //From the function name get the function as a string and extract the eval content from it.
    var evalValue = evalString.toString().split('Util.stripCustomFunctionFromObjectPrototype(Array);eval(''')[1].split(''') } catch (e) { alert(''A problem with the OnClick JavaScript for this button or link was encountered:')[0];
    console.log('the eval content are '+ evalValue);
    //the eval content are if(__fromScript){'r'n accountId = 10;'r'n}'r'n'r'n 'r'n 'r'n 
    eval(evalValue);// at this line I get a error stating 'Uncaught SyntaxError: Unexpected token ILLEGAL'

所以我决定用引号封装eval字符串,这根本不会产生结果。eval运行正常,但是accountId变量是undefined

eval(''''+evalValue+'''');
console.log('the account Id is '+ accountId);
//the account Id is undefined.

最后我硬编码了evalValue,然后代码按预期工作。

evalValue = 'if(__fromScript){'r'n accountId = 10;'r'n}'r'n'r'n ';
eval(evalValue);
console.log('the account Id is '+ accountId);
//the account Id is 10

eval中的动态引用没有被正确求值的任何原因

如果你只想要accountID,那么

var functionString = j$("[name=click_me]").prop("onclick");
var accountId = parseInt(functionString.split("accountId = ")[1]);

否则先删除所有'r'n