0

Hi I just can't figure this one out.

I need to use the window["evaluate string into js object"] because I am converting a web Application into a ChromeOS Chrome app and they do not let you use eval() to do their content security policy.

My problem is that for basic varibles it is fine, example:

var a = "foo";

var b = window["a"];

This will put "foo" into b no problem. But as soon as I have an object (both global or local) it doesn't work, so if 'a' was an object the code would like something like this:

a.test = "foo";

var b = window["a.test"];

That will not work.

Is there a reason for this? I can't seem to find much info on window[] in general so wondering if anyway has any insight or at least can point me in the right direction to look.

Thanks

4
  • You are trying to look into a property of a property of the window, you are interpreted as trying to fine the property (as the string) "a.test". Are you allowed to do window["a"].test? I'm also don't see why eval would help here. Commented Jul 15, 2016 at 0:06
  • window["a"]["test"] is how you would need to access it. Commented Jul 15, 2016 at 0:29
  • 1
    stackoverflow.com/questions/6393943/… Commented Jul 15, 2016 at 0:30
  • Thanks epascarello that worked for me, simple solution. Commented Jul 15, 2016 at 0:37

1 Answer 1

1

window[] doesn't work on namespaced functions, so if you try to evaluate window['a.test'] it would fail. A proper alternative is to use window['a']['test']. In case you're indefinite of number namespaced objects you're going to use, you can create a simple function that would split the string from . and create a window object for each part. Example :

var str = 'namespace.service.function';
var parts = str.split(".");
for (var i = 0, len = parts.length, obj = window; i < len; ++i) {
    obj = obj[parts[i]];
}
console.log(obj);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.