0
votes

I'm using eval to interpret some variables input.

Possible inputs are

"somevar"

"someobj.someprop['somekey'].someprop"

"window.someprop"

etc.

However I dont want it to 'execute' any action. Like calling any function, changing any value of anything, declaring any variable.

So those should not be accepted (and any that change state of anything):

alert()
var somewar = 0
mywar = somewar

Is it possible via native js?

My target is just to interpret complex input variable "address" and return it.

1
There are many QA on this topic, for example stackoverflow.com/questions/16564027/… - Denys Séguret
no it isn't. with es5 getters - it can run some logic. i would lock all these values into a single object. you might not want people to override window.document. - Daniel A. White
I've just realized that any code that change state must contain '(' or '=' - Adam Pietrasiak
You could possibly use a parser generator, but it's probably overkill for what you are doing: pegjs.majda.cz - Alex KeySmith

1 Answers

3
votes

For something like this, you may be better parsing the value.

var steps = input.match(/\['(?:[^']|\\.)+'\]|\["(?:[^"]|\\.)+"\]|[a-zA-Z0-9_]+/g);
var src = window;
var step;
while(step = steps.shift()) {
    if( step.charAt(0)) {
        // ['...'] or ["..."]
        step = step.substring(2,step.length-2);
    }
    src = src[step];
}
alert(src);

Since you're parsing out the string, there's no opportunity for malicious code to be executed.