代码未在javascript中执行eval

时间:2014-06-12 16:45:39

标签: javascript eval

我知道' 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中的动态引用的任何原因。

1 个答案:

答案 0 :(得分:0)

如果您只想要accountID,请执行

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

否则先删除所有\ r \ n