1

the iPad app I'm building has some behaviours that are driven by data. By data, I mean some javascript code embedded in the json file sent from server-side.

taken following as example:

if ((q12+q13+q14*2-2)>0){
    goto(q45);
    show(q1,q2);
}else{
    goto(q34);  
}

from iOS side, I know the values of q12/13/14, I want to execute the logic defined in javascript and receive the result, so that I can perform various interface behaviours. is it possible? I header with UIWebView I can get result from javascript, but my case the javascript is inside a json not an HTML url.

1
  • Be careful, you may fall foul of the AppStore TOS and your app will be barred. Commented Jan 5, 2013 at 15:48

1 Answer 1

1

It is indeed possible to have UIWebView execute arbitrary JavaScript and to capture any value returned as a result. I'm not sure I fully understand what the nature of code you're executing is, though, so I've just demonstrated the basic approach below. If you can provide more concrete details about the type of JavaScript logic you're hoping to execute I may be able to help more.

UIWebView *webView = [[UIWebView alloc] init];

NSNumber *q1 = @20;
NSNumber *q2 = @30;

// Create a simple JavaScript addition statement.
NSString *javascript;
javascript = [NSString stringWithFormat:@"%@ + %@", q1, q2];

// Note, the result will always be an NSString
NSString *result = [webView stringByEvaluatingJavaScriptFromString:javascript];
// result is @"50"

I also want to correct some terminology. You said "JavaScript code embedded in a JSON file". Actually, the JSON notation format can only contain name/value pairs. It can not contain executable JavaScript code. Perhaps you meant to say you were loading JavaScript files from the server?

Finally, when executing code loaded from outside your application like this you should always take appropriate technical design precautions to protect against malicious JavaScript that someone may try and trick your app into loading.

Sign up to request clarification or add additional context in comments.

1 Comment

They could be embedding escaped js code in the JSON data. But they are (either way) risking having their app rejected/removed from the appstore.

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.