简体   繁体   English

返回值javascript UIWebView

[英]return value javascript UIWebView

i'm trying to get the return value of a javascript function(for example: return "hello" ) with iPhone SDK. 我正在尝试使用iPhone SDK获取javascript函数的返回值(例如: return "hello" )。

On OS X the WebView method -stringByEvaluatingJavaScriptFromString returns a NSString containing the js function return value, but on the iPhone no value is returned. 在OS X上,WebView方法-stringByEvaluatingJavaScriptFromString返回包含js函数返回值的NSString,但在iPhone上没有返回任何值。

How can I solve this? 我怎么解决这个问题?


I found a private UIWebViewDelegate method 我找到了一个私有的UIWebViewDelegate方法

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

invoked when the alert() function is used in the js script. 在js脚本中使用alert()函数时调用。 So I can get the "return" value just by calling alert(myReturValue) . 所以我只需通过调用alert(myReturValue)即可获得“返回”值。

That doesn't solve my problem, because I need something in the public SDK. 这并不能解决我的问题,因为我在公共SDK中需要一些东西。

The return string is the result of the last Javascript statement. 返回字符串是最后一个Javascript语句的结果。 Do not put return in front of it! 不要return在它的前面!

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. 所以我不得不将UIWebView*添加到视图中(否则它会在之后崩溃),但不必将任何内容加载到webview中。

Notice that the last statement is just " f(); ", so the returned string will contain the result of the evaluation of f() . 请注意,最后一个语句只是“ f(); ”,因此返回的字符串将包含f()的求值结果。

I had the same problem when I tried call some functions from google maps API. 当我尝试从谷歌地图API调用一些函数时,我遇到了同样的问题。

There was a problem with returning objects, so I solved it by function toString(). 返回对象时出现问题,所以我通过函数toString()解决了它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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