简体   繁体   中英

Code not executing in eval in javascript

I'm aware that 'eval is evil' but in salesforce the standard functionality is using eval to execute a script on click of a button and this eval script is available on the page. Now, I am somehow getting the script and extracting the eval part from it. But I am not able to execute that eval string for some reason.

    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'

So I decided to encapsulate the eval string withing quotes which doesn't the results at all. The eval ran without any problem, but the accountId variable was undefined

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

At last I hardcoded evalValue and then the code worked as expected.

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

Any reasons why the dynamic reference in eval is not being evaluated correctly.

If you just want accountID, do

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

Otherwise remove all the \\r\\n first

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM