8

i'm trying to get the return value of a javascript function(for example: return "hello") with iPhone SDK.

On OS X the WebView method -stringByEvaluatingJavaScriptFromString returns a NSString containing the js function return value, but on the iPhone no value is returned.

How can I solve this?


I found a private UIWebViewDelegate method

- (void)webView:(id)fp8 runJavaScriptAlertPanelWithMessage:(id)fp12 initiatedByFrame:(id)fp16

invoked when the alert() function is used in the js script. So I can get the "return" value just by calling alert(myReturValue).

That doesn't solve my problem, because I need something in the public SDK.

2 Answers 2

29

The return string is the result of the last Javascript statement. Do not put return in front of it!

The minimum code that worked for me:

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
[self.view addSubview:webView];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:
                    @"function f(){ return \"hello\"; } f();"];
NSLog(@"result: '%@'", result); // 'hello'
[webView release];

So I had to add the UIWebView* to a view (otherwise it would crash afterwards), but didn't have to load anything into the webview.

Notice that the last statement is just "f();", so the returned string will contain the result of the evaluation of f().

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

Comments

6

I had the same problem when I tried call some functions from google maps API.

There was a problem with returning objects, so I solved it by function toString().

NSString *result = [webView stringByEvaluatingJavaScriptFromString:
                @"map.getBounds().toString();"];

1 Comment

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.